[removed] Make an array of value pairs form an array of values

前端 未结 8 1743
灰色年华
灰色年华 2021-01-06 08:40

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

[ 1, 5, 9, 21 ]

into this

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

I kn

8条回答
  •  抹茶落季
    2021-01-06 09:08

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

提交回复
热议问题