本文介绍了JavaScript:使值对的数组形成一组值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
[1,5,9,21] $ c $
$ p
$ [ 9],[9,21]]
我知道我可以 forEach
the数组并收集这些值以创建一个新数组。在 _。lodash
中没有使用 forEach
?
解决方案
您可以映射拼接数组并检查索引。如果它不为零,则取其前置,否则为原始数组的第一个元素。
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; }
更短的版本,如:
var array = [1,5,9,21],result = array.slice(1).map((a,i)=> [array [i],a]); console .log(result);
.as-console-wrapper {最大高度:100%!重要; top:0; }
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
?
解决方案
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; }
这篇关于JavaScript:使值对的数组形成一组值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!