本文介绍了最好的方式来通过值组相邻的数组项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有值的数组:

  [5,5,3,5,3,3]

什么是按价值计算,邻接组的最佳方法。结果应该是如下:

  [[5,5],[3],[5],[3,3]

当然,我可以遍历源阵列,并寻找下一个/ previous项目,如果它们是相同的,他们推到一个临时数组,这将是再攀新高结果数组。

不过,我喜欢写在功能的方式code。因此,也许有可能是一个更好的办法?


解决方案

您可以使用的方式:

\r
\r

VAR的结果= [5,5,3,5,3,3]。减少(函数(preV,CURR){\r
    如果(prev.length&放大器;&安培; CURR === preV [prev.length - 1] [0]){\r
        preV [prev.length - 1] .push(CURR);\r
    }\r
    其他{\r
        prev.push([CURR]);\r
    }\r
    返回preV;\r
},[]);\r
\r
警报(JSON.stringify(结果));

\r

\r
\r

Assume we have an array of values:

[5, 5, 3, 5, 3, 3]

What is the best way to group them by value and adjacency. The result should be as follows:

[ [5,5], [3], [5], [3,3] ]

Of course, I can loop through the source array and look for the next/previous item, and if they are the same, push them to a temporary array that will be then pushed to the resulting array.

But I like to write code in functional way. So maybe there could be a better way?

解决方案

You can use Array.prototype.reduce method:

var result = [5, 5, 3, 5, 3, 3].reduce(function(prev, curr) {
    if (prev.length && curr === prev[prev.length - 1][0]) {
        prev[prev.length - 1].push(curr);
    }
    else {
        prev.push([curr]);
    }
    return prev;
}, []);

alert( JSON.stringify(result) );

这篇关于最好的方式来通过值组相邻的数组项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-14 07:33