skip to Main Content
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


  1. 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 as result.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.

    if (result.length === 0) {
        result.push(-1);
      }
    
    Login or Signup to reply.
  2. For me it works when you check "result" array length instead of comparing result with empty array:

      if (result.length == 0) {
        result.push(-1);
      }
    

    It means that Javascript somehow cannot lay identity between empty array and [] It possibly considers [] as being another different instance…

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search