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!!

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay