B
B
Blunker2017-05-21 07:57:38
JavaScript
Blunker, 2017-05-21 07:57:38

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}
    ]
];

Help me come up with an algorithm

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey Sokolov, 2017-05-21
@Blunker

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 ) // 

If you want to pair them not by position in the original array, but by the distance between them on the field, this is a completely different story. Refine your question.

A
Arman, 2017-05-21
@Arik

https://gist.github.com/subimage/2419212

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question