-1

I've created a method in my utils.ts to delete an element from an array.

public static deleteElementFromArray<T>(list: T[], element: T): T[] {
    if (!list) {
      return [];
    }
    const index = list.indexOf(element);
    if (index > -1) {
        list.splice(index, 1);
    }
    return list;
}

a friend of mine tell me that he uses filter to filter the list and exclude the element.

users = users.filter(u => u !== toto);

I wonder what you think of this and if you have a better solution

pushkin
  • 7,514
  • 14
  • 41
  • 74
dev34fr
  • 13
  • 2
  • `filter` is perfectly fine to use. Do you have any specific concerns with it? It's more readable certainly – pushkin Apr 19 '18 at 15:10
  • 1
    They both do the same thing in this instance, `splice` is probably more efficient though by working on the array directly. `filter` rebuilds a new array based on the predicate you supply. – Lloyd Apr 19 '18 at 15:10
  • If you process a few thousand arrays with a few thpusand elements, use the first as it is faster. Otherwise use the last one as it is pure and more readable. – Jonas Wilms Apr 19 '18 at 15:16
  • I'm not up to speed with JavaScript so this is an honest question: Is this mixing Java and JavaScript? Does `public static` actually exist in JS along with generic types (``)? – Matt Apr 19 '18 at 15:20
  • @Matt Actually this used to be tagged Typescript, but since it's really a JavaScript question, I replaced TypeScript with JavaScript. Arguably I should add the typescript tag back in. – pushkin Apr 19 '18 at 15:23

2 Answers2

0

Either solution is fine, a more detailed answer can be found here: How do I remove a particular element from an array in JavaScript?

Just take in consideration that the notation for anonymous function '=>' may not be implemented in al browsers.

0
  • splice - Remove an element from array
  • filter - Not modifying original array and will create new filtered array

See this link: https://medium.com/@justintulk/javascript-performance-array-slice-vs-array-filter-4573d726aacb
Test: https://jsperf.com/array-splice-vs-array-filter/1

Alvin
  • 240
  • 4
  • 23