Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript : Make an array of value pairs form an array of values

Is there an elegant, functional way to turn this array:

[ 1, 5, 9, 21 ]

into this

[ [1, 5], [5, 9], [9, 21] ]

I know I could forEach the array and collect the values to create a new array. Is there an elegant way to do that in _.lodash without using a forEach?

like image 585
pyronaur Avatar asked Dec 13 '22 23:12

pyronaur


1 Answers

You could map a spliced array and check the index. If it is not zero, take the predecessor, otherwise the first element of the original array.

var array = [1, 5, 9, 21],
    result = array.slice(1).map((a, i, aa) => [i ? aa[i - 1] : array[0], a]);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

An even shorter version, as suggested by Bergi:

var array = [1, 5, 9, 21],
    result = array.slice(1).map((a, i) => [array[i], a]);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
like image 180
Nina Scholz Avatar answered Dec 22 '22 00:12

Nina Scholz