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
  • 4,044
  • 9
  • 32
  • 39
Brixsta
  • 605
  • 12
  • 24

4 Answers4

1

Try this:

function removeElement(array, discarder) {

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

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

}
Shuvo
  • 1,253
  • 9
  • 18
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
  • 2,144
  • 15
  • 26
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
  • 196,159
  • 39
  • 305
  • 313
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
  • 177
  • 1
  • 11