0

I was asked to write a function that adds an element to the end of an array. However, if the added element has the same value as one of the elements in the array, the element should not be added to the array. Like add([1,2],2) should return [1,2] only

My code is:

  function add (arr, elem){ 

      if (arr.indexOf(elem) != -1){
           return arr;
      }

      else {

           let newArr = arr.push(elem); 
           return newArr; 
      }

  }

  console.log(add([1,2],3)); // here returns a number '3' instead of an array[1,2,3]

Can anyone explain why I got a number instead of the array 'newArr' in else?

  • Because according to the [docs](https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Array/push) `push` returns the new length of the array – derpirscher Jul 14 '21 at 19:58
  • `array.push()` returns the length of the array. If you want the whole array, just have your function return `arr` and don't bother setting up `newArr`. – Scott Marcus Jul 14 '21 at 19:58

2 Answers2

1

Array.push does not return the whole array but the count of the new array

For example:

const colors = ['red', 'blue', 'yellow'];
const count = colors.push('green');
console.log(count); // expected output: 4
console.log(colors); // expected output: Array ["red", "blue", "yellow", "green"]
  • Since you return colors.push('green') in your case, you get the number of the elements in the new array after array push operation.
Nothingbutageek
  • 357
  • 1
  • 11
0

You still have to return arr if you want it to show your existing values.

function add (arr, elem){ 
      if (arr.indexOf(elem) != -1){
           return arr;
      }
      arr.push(elem); 
      return arr;
}
Vladimir Mujakovic
  • 650
  • 1
  • 7
  • 21