DEV Community

Nashmeyah
Nashmeyah

Posted on

JS Objects: adding & updating key value pairs

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"]
]
Enter fullscreen mode Exit fullscreen mode

Our goal is to have a JavaScript Object that looks something like this

{
  "a":0,
  "b":3,
  "c":1
}
Enter fullscreen mode Exit fullscreen mode

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"]
Enter fullscreen mode Exit fullscreen mode

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
}
Enter fullscreen mode Exit fullscreen mode

I hope this made sense, let me know if there is anything that needs extra clarification. Byee!!

Top comments (0)