I was trying to find as a dictionary (JS object) how many times each of the elements appears in some list. For example, the appearance of 1 in the list [1,1,2,2,1,3,4] is 3, because there are three ones in the list. In python I would implement this in the following way:
l = [1,1,2,2,1,3,4]
apr = dict()
for e in l:
if (e in apr.keys()):
apr[e] += 1
else:
apr[e] = 1
In javascript I decided to do
var arr = [1,1,2,2,1,3,4];
var vals = {};
for (let e of arr){
if (e in Object.keys(vals)){
vals[e] = vals[e] + 1;
}
else{
vals[e] = 1;
}
}
// vals = { '1': 2, '2': 1, '3': 1, '4': 1 }
which is obviously wrong. Then I tried if (Object.keys(vals).includes(e)){
instead, and it didn't work either. At the very end I implemented my own function my_in
, and the progem worked:
function my_in(val,arr){
for (i = 0; i<=arr.length; i++){
if (val==arr[i]){
return true;
}
}
return false;
}
var arr = [1,1,2,2,1,3,4];
var vals = {};
for (let e of arr){
//if (Object.keys(vals).includes(e)){
// if (e in Object.keys(vals)){
if (my_in(e, Object.keys(vals))) {
vals[e] = vals[e] + 1;
}
else{
vals[e] = 1;
}
}
console.log(vals);
But I am still confused why did the first two tries didn't work. Is there anything I should be aware of when using in
or includes()
?
You need to use in
operator with the object, not with an array this would check the indices.
For example by using an an array of keys
vals = { 1: 1 }
keys = Object(vals) // ['1']
if (1 in keys) performs
-> 1 in { 0: 1, length: 1 }, because there is only index zero with value one
-> false
var arr = [1, 1, 2, 2, 1, 3, 4];
var vals = {};
for (let e of arr) {
if (e in vals) { // check with object
vals[e] = vals[e] + 1;
} else {
vals[e] = 1;
}
}
console.log(vals);