I have an array containing duplicate elements. What I need is to get those duplicate elements to new sub-arrays.
For example:
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]
Thanks.
You could group the array by the values.
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);
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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.