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.