Home > Blockchain >  JS - Array of arrays
JS - Array of arrays

Time:09-23

I have some array:

let someArr = [["A","B"],["A","C"],["C","A"],["B","D"]]

I want return object , the object include name and his counter(how many times the name was repeat at all inner arrays.

Expected output is : {"A":3, "B":2,"C":2,"D":1}

initial object:

let returnObj = {name:"",count:0}

and now i thinking do that:

someArr.foreach(arr => {
    return (
        arr.map(item => {
            //check if item in returnObj then count  ,
            // but how can i check if i have many names and its counter?
            //Maybe I need return array of objects?
            //else add this item to returnObj and count  
       })
    );
})

Have you other idea how can I count the names?

CodePudding user response:

This what I came up with for you - hope this is what you are after:

var arr = [["A","B"],["A","C"],["C","A"],["B","D"]]

var obj = arr.flat().reduce((acc, item) => ({...acc, [item]:(acc[item]||0)   1}), {})

console.log(obj)

First, flattens the array of arrays, and iterate everything using a reduce method, which makes for the shortest solution.

Inside the reduce the modified accumulator is returned at each iteration, with a new count for the current scanned item.

If an item (as key) was not found in the accumulator, it means it is the first time it's been encountered, and should then be treated as 0 and simply add 1 to it. Else, just use the last counted value for that key (item) and add 1 to it.


Bonus - you can also write the reduce differently, without destructuring on every iteration, always keeping the same reference to the original accumulator:

arr.flat().reduce((acc, item) => (acc[item] = (acc[item]||0)   1, acc), {})
  • Related