0

I have an array [2, 2, 4, 3] and I am trying to obtain a dictionary thats something like {2:[0,1], 3:3, 4:2} that is basically a dictionary which contains the items in the array as key and its indices as the value, if there are multiple indices with the same item, then store the value in the dictionary as an array else as a normal value.

var arr = [2,2,4,3];
var dict={};
var len=arr.length;
for(var i=0; i<len; i++) {
   dict[arr[i]] = i;
}

console.log(dict);

The above snippet only take the latest instance of the item in the array as key and stores it as value, is there a way to make the value of the dictionary as an array if there are duplicate multiple items in the array. Also, I am a beginner in javascript so please ignore if its a stupid question.

4
  • 1
    Is it absolutely necessary, that numbers, which occur only once, get unpacked, instead of e.g. "3: [3]"? Sure, it's possible, but why? Commented Jul 25, 2018 at 21:56
  • Expanding on what ASDFGerte said, it just makes things harder and can cause many functions to error when trying to process it. It's much easier if you keep as a 1 element array to stay consistent. Commented Jul 25, 2018 at 21:58
  • FYI, dictionaries are called objects in Javascript. Commented Jul 25, 2018 at 22:03
  • @ ASDFGerte As I have to search the dictionary later and find the indices which matches the result of an operation performed later. @Barmar thanks for that info Commented Jul 25, 2018 at 22:07

3 Answers 3

1

var arr = [2,2,4,3];
var dict={};
var len=arr.length;
for(var i=0; i<len; i++) {
   if(dict[arr[i]] !== undefined)
   {
     if(Array.isArray(dict[arr[i]]))
     {
       dict[arr[i]].push(i);
     }
     else
     {
       dict[arr[i]] = [dict[arr[i]]];
       dict[arr[i]].push(i);
     }
   }
   else
     dict[arr[i]] = i;
}

console.log(dict);

Sign up to request clarification or add additional context in comments.

3 Comments

thank you for the answer this is what I was looking for
I know its dumb, but can you please explain why you did dict[arr[i]] = [dict[arr[i]]];? coz even if I do dict[arr[i]] = [];, and then do dict[arr[i]].push(i); that creates an an array and inserts index 1, but not the index 0, can you please explain why?
That first line is creating a new array with the existing value as the first value in the array. When that line is called, dict[arr[i]] == 0, so [dict[arr[i]]] == [0].
1

An alternative is using the function reduce to group values with indexes.

let arr = [2, 2, 4, 3],
    result = arr.reduce((a, c, i) => {
      let current = a[c];
      if (current || current === 0) {
        if (Array.isArray(current)) current.push(i);
        else a[c] = [current, i];
      } else a[c] = i;
      
      return a
    }, {});
    
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Comments

1

It can be done very simply

const dict = array.reduce((result, value, index) => {
  if (!result[value]) {
    result[value] = [index];
  } else {
    result[value].push(index);
  }
  return result;
}, {});

Or, immutably:

const dict = array.reduce((result, value, index) => ({
  ...result,
  [value]: [...(result[value] || []), index]
}), {});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.