将数组拆分为匹配值的数组

将数组拆分为匹配值的数组

本文介绍了将数组拆分为匹配值的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类似于以下值的数组:

I have an array of values similar to:

["100", "330", "22", "100", "4.7", "0.01", "0.01", "330", "0.01", "100", "47", "22", "100", "0.01"]

使用JavaScript,我想将此数组拆分为多个数组,其中只有匹配的字符串在这些数组中,如下所示:

Using JavaScript I would like to split this array into a number of arrays where only matching strings are in those arrays like this:

["100", "100", "100"]
["330", "330"]
["22", "22"]
["0.01", "0.01", "0.01", "0.01"]
["47"]
["4.7"]

任何对此的帮助将不胜感激!谢谢!

Any help with this would be much appreciated! Thanks!

推荐答案

您可以使用 Map 并获取值作为结果.

You could collect with a Map and get the values as result.

由内而外:

  • 使用 Array#reduce data ,并使用 Map 实例作为 initialValue .
  • 作为回调,请使用 Map#set 并收集每个组的值.

  • Use Array#reduce with data and use a Map instance as initialValue.
  • As callback take Map#set and collect the values for each group.

其他方法:

从地图中获取值并将其用作参数

Get the values from the map and use it as parameter for

var data = ["100", "330", "22", "100", "4.7", "0.01", "0.01", "330", "0.01", "100", "47", "22", "100", "0.01"],
    result = Array.from(data
        .reduce((m, v) => m.set(v, [...(m.get(v) || []), v]), new Map)
        .values()
    );

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

这篇关于将数组拆分为匹配值的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 00:26