function map(arr) {
let m = new Map();
arr.forEach((num) => {
m.set(`${num}`, m.get(`${num}`) == undefined ? 1 : m.get(`${num}`) + 1);
});
let result = [];
m.forEach((cnt, num) => (cnt > 1 ? result.push(+cnt) : ""));
if (result == []) {
result.push(-1);
}
console.log(result);
}
map([1, 2, 3, 3, 3, 3, 4, 4]); // [ 4, 2 ]
map([3, 2, 4, 4, 2, 5, 2, 5, 5]); // [ 3, 2, 3 ]
map([3, 5, 7, 9, 1]); // []
I want to [-1] if there isn’t duplicated numbers.
But -1 is not push to result array. Why?
I want to know better code to count duplicated numbers to front to back.
result == [] ? result.push(-1) : "";
Or tried unshift() instead using push() method.
But it’s same output.
2
Answers
Your if condition check is wrong. The condition
result == []
will evaluate to false, even if result is an empty array. To compare the contents of arrays, you should use other methods such asresult.length === 0
.Arrays are reference types, and when comparing them with the equality operator, JavaScript checks if the references to the arrays are the same, rather than comparing their contents.
Replace your if condition with code below and it should work.
For me it works when you check "result" array length instead of comparing result with empty array:
It means that Javascript somehow cannot lay identity between empty array and [] It possibly considers [] as being another different instance…