使用includes()对对象字符串进行分组



我有一个对象。它看起来如下:

var records = ["test1 name1", "test2 name2", "test1 name3", "test1 name4"];

我想按组字段对这些数据进行分组,并获得此对象:

var obj = [["test1 name1", "test1 name3", "test1 name4"], ["test2 name2"]];

如何使用测试词中的includes()对字符串对象进行分组?

使用.split()后,您就可以引用返回数组的第一个元素,您可以使用它将字符串分组到子数组中。

使用.reduce().find():

const records = ["test1 name1", "test2 name2", "test1 name3", "test1 name4"];
const result = records.reduce((a, c) => {
const found = a.find(e => e[0].split(' ')[0] === c.split(' ')[0]);

if (found) found.push(c);
else a.push([c]);
return a;
}, []);
console.log(result);

我希望这能有所帮助!

最新更新