assigning a key name from an array

Advertisements

I can’t seem to make the key equal to the name of the index value of the array of names being passed in.

What Im trying to do:

create a key value of names and numbers to keep track of how many duplicate names I have.

input/output:

names = [bob, joe, jill, bob, bill, bill]

the output would be {bob:2, joe:1, jill:1, bill:2}

I haven’t gotten to this part of the code yet. currently just trying to get the keys right. But it should paint a picture of what I’m trying to do.

the Issue I’m having:

I cant seem to create keys for each name in my set

what I did initially:

myset.add({names[i]:0})

which I changed to a variable called keyname that is being assigned right under my forloop.

this changed nothing.


function solution(names) {
    const myset = new Set();
    for(let i=0; i<names.length; i++){
        let keyname = names[i];
        if(myset.has(names[i])){
            console.log("already includes");
        }
        else(
            myset.add({
                keyname:0
            })
        )
    }
    console.log(myset);
}

Console:

Set(5) {
  { keyname: 0 },
  { keyname: 0 },
  { keyname: 0 },
  { keyname: 0 },
  { keyname: 0 }
}

>Solution :

Set is just collection of unique values. If you are adding an object then It won’t be equal to any other object unless both are not referentially same.

Set objects are collections of values. You can iterate through the
elements of a set in insertion order. A value in the Set may only
occur once; it is unique in the Set’s collection.

If you just have to count the occurrences of string then you can do this either using plain object or Map as:

function solution(names) {
  const dict = {};
  
  for (let i = 0; i < names.length; ++i) {
    if (!dict[names[i]]) dict[names[i]] = 1;
    else ++dict[names[i]];
  }

  console.log(dict);
}

solution(["bob", "joe", "jill", "bob"]);
function solution(names) {
  const map = new Map();
  names.forEach((name) =>
    !map.has(name) ? map.set(name, 1) : map.set(name, map.get(name) + 1)
  );
  console.log(map);
}

solution(["bob", "joe", "jill", "bob"]);

Leave a ReplyCancel reply