Skip to content

I am trying to solve a challenge from

I am trying to solve a challenge from

Write a function add that adds an element to the end of an array. However, the element should only be added if it is not already in the array.

Example: add([1, 2], 3) should return [1, 2, 3] and add([1, 2], 2) should return [1, 2].

why didn’t work this code ?

function add(Sarray, nosarray) {
  if (Sarray.indexOf(nosarray) > -1) {
    return Sarray;
  } else {
    return Sarray.push(nosarray);

but returns number 2. I can’t Understand it if .push(). The new element is passed as a parameter and is added to the end of the array. why in my code didn’t work ?


Please read the reference for Array.prototype.push method.

Method adds element to the end of array and returns length of an array. You need to return array itself – not result of push method.

return Sarray;