如何从数组中获取包含相同元素的子数组?

How to get sub-arrays containing same elements from an array?

我有一个包含重复元素的数组。我需要的是将那些重复的元素放到新的子数组中。

例如:

I have the main array, array = [ a, b, c, a, d, c, c, b, a ]

what I need is to get this array divide into new sub-arrays dynamically like below:

subArray1 = [ a,a,a]
subArray2 = [b,b]
subArray3 = [c,c,c]
subArray4 = [d]

谢谢。

let array = ['a', 'b', 'c', 'a', 'd', 'c', 'c', 'b', 'a'];

function divide(array) {
    let allArrays = [];
    for (let i = 0; i < array.length; i++) {
       if(!allArrays.flat().includes(array[i])) 
       allArrays.push(array.filter(el => el === array[i]));
    }
    return allArrays;
}

let [subArray1,subArray2,subArray3,subArray4] = divide(array);

您可以按值对数组进行分组。

const
    array = ['a', 'b', 'c', 'a', 'd', 'c', 'c', 'b', 'a'],
    grouped = Object.values(array.reduce((r, v) => {
        (r[v] ??= []).push(v);
        return r;
    }, {}));

console.log(grouped);