Answer the question
In order to leave comments, you need to log in
How to take elements in pairs?
There is an array consisting of objects with coordinates. You need to make a new array which will consist of pairs of neighboring objects, for example, there is an array [{0,1}, {1,1}, {4,1}, {5, 7}]
. At the output, you need to get an array of two elements:
[
[
{0,1},
{1,1,}
],
[
{4,1},
{5,7}
]
];
Answer the question
In order to leave comments, you need to log in
You can sequentially split into pairs, for example, like this:
var data = [{x:0,y:1}, {x:1,y:1}, {x:4,y:1}, {x:5, y:7}]
, pairs = []
, i
;
for( i = 0; i < data.length; i++) { // перебираем входные элементы
if( i % 2 === 0) pairs.push([]); // четный – добавляем новую пустую «пару»
pairs[ pairs.length - 1].push( data[i]); // в последнюю пару добавляем элемент
}
JSON.stringify( pairs ) //
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question