Hello lovely devs, recently I was working on an algorithm. The task was to take a nested array and keep track of how many times an element appears and keep count.
Here is an array of arrays that we will be using to create a data obj to show an example of how to add and update key vlues
const listOfStrings = [
["n","a","s","h"],
["l","o","o","k","s"],
["h","o","t"]
]
Our goal is to have a JavaScript Object that looks something like this
{
"a":0,
"b":3,
"c":1
}
the first step that I think is simpler to do is since we have an array of arrays, we can us a js method and flatten them.
let stringData = listOfStrings.flat()
// --> ["n","a","s","h","l","o","o","k","s","h","o","t"]
Now that we have that done, we can create a loop and have conditionals to determine if we already encountered a letter or not. If we did then we add one to the count.
const objCountforStringArrays = () =>{
let stringData = listOfStrings.flat()
let stringDataCount = {}
for(let i = 0; i < stringData.length; i++){
if(stringDataCount.hasOwnProperty(stringData[i])){
// updating value for key stringData[i] by 1
stringDataCount[stringData[i]]++ ;
}else{
// adding a new key/value in the obj
stringDataCount[stringData[i]] = 1;
}
}
return stringDataCount
}
I hope this made sense, let me know if there is anything that needs extra clarification. Byee!!
Top comments (0)