Home > OS >  Filter out and count duplicates in array, return object
Filter out and count duplicates in array, return object

Time:06-09

I have data that looks like this

let countsRaw= [ 7, 8, 7, 6] 

I would like the output to look like this

let countsObj = {
6: {count :  1, filterState : false},
7: {count :  2, filterState : false},
8: {count :  1, filterState : false}, 
}

I have tried numerous different orientations but am not getting the output I expect from the code below, any explanation or direction would be greatly appreciated.

    let countsObj = {};
            countsRaw.forEach((x) => ({
                count: (countsObj[x] = (countsObj[x] || 0)   1),
            }));

the result is

countObj = {6: 1, 7: 2, 8: 1}

I can't figure out why the nested objects are not being added.

thansk (:

CodePudding user response:

You just forgot to add the nested object.

const countsRaw = [ 7, 8, 7, 6];
const output = {};
countsRaw.forEach(e => {
  if (e in output) {
    output[e].count  = 1;
    }
  else output[e] = { count: 1, filterState: false};
});

console.log(output);

CodePudding user response:

Heres what I would do:

let duplicatesRemoved = [...new Set(array)].sort();

let countsObj = {};
    
duplicatesRemoved.forEach((v,i) => {
    countsObj[v] = {count: i, filterState: false}
});
  • Related