0

for some reason only the element with the index of 0 is being removed. and also, can i access it more then once using the splice() method?

function myFunction(arr, val) {
  for (let i = 0; i < arr.length; i++) {
    if (arr[i] === val) {
      return arr.splice(i);
    }
  }
}

console.log(myFunction([2, 3, 4, 3, 2, 1], 3));
Znatok
  • 23
  • 6
  • Does this answer your question: https://stackoverflow.com/questions/500606/deleting-array-elements-in-javascript-delete-vs-splice – Abrar Hossain Dec 19 '21 at 10:37
  • iterating from start and removing some items makes the index invalid. you could iterate from the end and keep the right index. – Nina Scholz Dec 19 '21 at 10:38
  • Do you need to mutate an original array or just get an array without some values? In the second case, you can just filter an array: `[2, 3, 4, 3, 2, 1].filter((item) => item !== 3)` `[2, 4, 2, 1]` – A1exandr Belan Dec 19 '21 at 10:44
  • Refer to MDN's [`splice` documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice). Your code says "remove all the elements in the array from `i` onward and return them as a new array." I don't think that's what you meant to do. – T.J. Crowder Dec 19 '21 at 10:45
  • Thanks. new array without the values will do. So i will use filter() – Znatok Dec 19 '21 at 10:55

0 Answers0