I am trying to create a little project where I can count the number of elements in an array. This part I have already done. My question is how can I fix a counting problem? I’m using a mapping method to get my element occurrence counter, but I want to put the data into an array. The only way I know how is to take the data from the mapping with .get. They way I’m doing it is by using this first part here:
let winners = [1, 2, 3, 2]; let nullArray = []; let mode = new Map([...new Set(winners)].map( k => [k, winners.filter(t => t === k).length] )); for (let n in winners) { nullArray.push(mode.get(winners[n])); console.log(nullArray); }
However, this will *n push matches. Like, if you have l=[1,2,2], because l[1]=2, and l[2]=2, they will be pushed into the nullArray as 2, however, it will also push l[2] and l[1] as the values are different. If you have three matches, it would duplicate 3 times, and so on. To counter this, I tried making a detector that would calculate when the same numbers in the nullArray are from the same copy but in a different order. To do this, I used the code I have below (combined with the original code)
let winners = [1, 2, 3, 2]; let nullArray = []; let mode = new Map([...new Set(winners)].map( k => [k, winners.filter(t => t === k).length] )); for (let n in winners) { nullArray.push(mode.get(winners[n])); console.log(nullArray); } for (let num in nullArray) { for (let c in nullArray) { if (nullArray[num] === nullArray[c] && winners[num] === winners[c]) { nullArray.splice(num, 1); } console.log(nullArray); } }
However, whenever I try this, the specific output on this array is [2,2]. How could I make a general solution that will eliminate all duplicate copies, only leaving a single copy of the number count (which in the case of [1,2,3,2], I would want nullArray=[1,2,1] as an output)
Advertisement
Answer
You can do something like this.
If you don’t care about the order, you can just do the following.
const remove_dup_and_count = (winners = [1, 2, 3, 2]) =>{ let map = {} //count elements for (let n in winners) { const curr_val = winners[n] //duplicate, so we increment count if(curr_val in map) map[curr_val] += 1 //first seen, so we start at 1 else map[curr_val] = 1 } //lets grab the array of all keys in map const keys_arr = Object.keys(map) let count_arr = [] for(let i of keys_arr){ count_arr.push(map[i]) } return count_arr } console.log(remove_dup_and_count())
If you care about the order, this is your best bet:
const remove_dup_and_count = (winners = [1, 2, 3, 2]) =>{ let map = new Map() //count elements for (let n in winners) { const curr_val = winners[n] //duplicate, so we increment count if(map.get(curr_val)) map.set(curr_val, map.get(curr_val) + 1) //first seen, so we start at 1 else map.set(curr_val,1) } let count_arr = [] //lets grab the array of all keys in map for (const [key, value] of map) { count_arr.push(value) } return count_arr } console.log(remove_dup_and_count())