1
/*

***If all the elements match, it should return an empty array.

***If an empty array is passed in, it should return an empty 
array.

*/



function removeElement(array, discarder) {

  if(array.length === 0) {
    array = [];
  }

  for(var i=0; i<array.length; i++) {
    if(discarder === array[i]) {
      array.splice(i, 1);
    }



    return array;
  }
}

var output = removeElement([1, 2, 3, 2, 1], 2);
console.log(output); // --> [1, 3, 1]

Does anyone know how I can delete an array element I specify in the discarder argument?

Also, I need to return an empty Array if all elements are the same. I've been stuck on this for way too long.

Pejman Kheyri
  • 1,389
  • 6
  • 13
  • 22
Brixsta
  • 373
  • 6
  • 21

4 Answers4

1

Try this:

function removeElement(array, discarder) {

  if(array.length === 0) {
    return array;
  }

  return array.filter(item => item !== discarder);

}
Shuvo
  • 926
  • 7
  • 14
1

You need to use Array.filter

const removeElement = (array, discarder) => array.filter(value => value !== discarder);

var output = removeElement([1, 2, 3, 2, 1], 2);
console.log(output);
Mohammad Faisal
  • 1,230
  • 8
  • 19
1

const removeElement = (arr, ...rem) => arr.filter(x => !rem.includes(x));

console.log(removeElement([], 2));                    // []
console.log(removeElement([1, 2, 3, 2, 1], 2));       // [1,3,1]
console.log(removeElement([1, 2, 3, 2, 1], 2, 3));    // [1,1]
console.log(removeElement([1, 2, 3, 2, 1], 2, 3, 1)); // []
Roko C. Buljan
  • 164,703
  • 32
  • 260
  • 278
0

Using splice, this would work:

function removeItemFirst(arr, value) {
  var index = arr.indexOf(value);
  if (index > -1) {
    arr.splice(index, 1);
  }
  return arr;
}

function removeItemAll(arr, value) {
  var i = 0;
  while (i < arr.length) {
    if (arr[i] === value) {
      arr.splice(i, 1);
    } else {
      ++i;
    }
  }
  return arr;
}

But better way is to use .filter() as mentioned in @Shuvo's answer.

notnotparas
  • 159
  • 1
  • 9