在JS中将数组中的相同值分组到数组中

Vis*_*kur 3 javascript arrays

如何将数组中的相同数字分组到数组中?

我有以下数字数组:

var arr = [1,1,1,1,2,2,3,3,3,4,5,5,6];
Run Code Online (Sandbox Code Playgroud)

我的输出应该是

[[1,1,1,1],[2,2],[3,3,3],4,[5,5],6]
Run Code Online (Sandbox Code Playgroud)

Ben*_*ves 7

我最近遇到了这个问题。提供的答案效果很好,但我想要一种更简单的方法,而不必从 lodash 或 underscore 导入。这是 tl;dr(太长没读):

  const groupedObj = arr.reduce(
    (prev, current) => ({
      ...prev,
      [current]: [...(prev[current] || []), current],
    }),
    {}
  );

const groupedObjToArr = Object.values(groupedObj);
Run Code Online (Sandbox Code Playgroud)

解释

我们想要创建一个对象,其中每个唯一数字都是该对象中的属性或键,并且它的值是所有相同数字的数组。对于提供的数组:

const arr = [1,1,1,1,2,2,3,3,3,4,5,5,6];
Run Code Online (Sandbox Code Playgroud)

我们的目标应该是:

{ 
    1: [1,1,1,1],
    2: [2,2],
    3: [3,3,3],
    4: [4],
    5: [5,5],
    6: [6]
}
Run Code Online (Sandbox Code Playgroud)

为此,我们将减少提供的数组(.reduce可以通过搜索数组减少在 MDN 上找到有关方法的文档)。

arr.reduce((previous, current, idx, array) => {}, {});
Run Code Online (Sandbox Code Playgroud)

快速分解Reduce

Reduce 是 Array 上的一个方法,它带有两个参数:回调初始值。Reduce 为我们的回调提供了四个参数:一项,在开始时与我们的初始值相同,因此在这种情况下previous{}在reduce 的第一次迭代中;current是我们在迭代中使用的数组中的值;index是当前元素的索引;并且,数组是原始数组的浅拷贝。出于我们的目的,我们不需要索引或数组参数。

当我们迭代数组时,我们希望将数字或元素设置为对象中的键:

arr.reduce((previous, current) => {
    return {...prev, [current]: []};
}, {});
Run Code Online (Sandbox Code Playgroud)

这就是前几次迭代的样子:

// 1 (first element of arr)
// returns {...{}, [1]: []} => {1: []}

// 1 (second element of arr)
// returns {...{ 1: [] }, [1]: []} => {1: []}  we have a duplicate key so the previous is overwritten

// 1 (third element of arr)
// returns {...{ 1: [] }, [1]: []} => {1: []}  same thing here, we have a duplicate key so the previous is overwritten

// ...

// 2 (fifth element of arr)
// returns {...{ 1: [] }, [2]: []} => {1: [], 2: []}  2 is a unique key so we add it to our object
Run Code Online (Sandbox Code Playgroud)

我们有一个对象,其中包含与数组中所有数字相匹配的所有唯一键。下一步是用与该键匹配的所有元素填充每个“子数组”。

arr.reduce((previous, current) => {
    return {...prev, [current]: [current]}; // n.b. [current]: allows us to use the value of a variable as a key in an obj where the right side [current] is an array with an element current
}, {});
Run Code Online (Sandbox Code Playgroud)

这并不能满足我们的需要,因为每次迭代都会覆盖前一个子项,而不是附加到其中。这个简单的修改修复了:

arr.reduce((previous, current) => {
    return {...prev, [current]: [...prev[current], current]};
}, {});
Run Code Online (Sandbox Code Playgroud)

返回prev[current]与匹配当前项的键关联的数组。展开数组...允许我们将当前项附加到现有数组中。

// 1 (second element of arr)
// returns {...{ 1: [1] }, [1]: [...[1], 1]} => {1: [1, 1]}  
// 1 (third element of arr)
// returns {...{ 1: [1, 1] }, [1]: [...[1, 1], 1]} => {1: [1, 1, 1]}

// ...

// 2 (fifth element of arr)
// returns {...{ 1: [1,1,1,1] }, [2]: [...[], 2]} => {1: [1,1,1,1], 2: [2]}
Run Code Online (Sandbox Code Playgroud)

很快我们就会发现一个问题。我们无法current索引undefined. 换句话说,当我们最初启动时,我们的对象是空的(记住我们的reduce的初始值是{})。我们要做的是为这种情况创建一个后备,只需添加|| []含义或空数组即可完成:

// let's assign the return of our reduce (our object) to a variable
const groupedObj = arr.reduce((prev, current) => {
    return {...prev, [current]: [...prev[current] || [], current]};
}, {});
Run Code Online (Sandbox Code Playgroud)

values最后,我们可以使用类型上的方法将此对象转换为数组ObjectObject.values(groupedObj)

断言

这是一个快速的小断言测试(不全面):

const arr = [1,1,1,1,2,2,3,3,3,4,5,5,6];
  const groupedObj = arr.reduce(
    (prev, current) => ({
      ...prev,
      [current]: [...(prev[current] || []), current],
    }),
    {}
  );

const groupedObjToArr = Object.values(groupedObj);

const flattenGroup = groupedObjToArr.flat(); // takes sub arrays and flattens them into the "parent" array [1, [2, 3], 4, [5, 6]] => [1, 2, 3, 4, 5, 6]
const isSameLength = arr.length === flattenGroup.length;
const hasSameElements = arr.every((x) => flattenGroup.includes(x)); // is every element in arr in our flattened array
const assertion = isSameLength && hasSameElements;

console.log(assertion); //should be true
Run Code Online (Sandbox Code Playgroud)