1

What's the best way to remove the last element from an array if it matches a particular value?

For instance:

components = dedupeLast(components, '<app-builder-placeholder></app-builder-placeholder>');

function dedupeLast(a, target) {
  for(let i = 0; i < a.length; i++){
    if (i === a.length) {
      if(a[i] === target)
      a.splice(i, 1);
    }
  }
}
methuselah
  • 11,964
  • 41
  • 148
  • 269
  • Not a `for` loop o.O Your function tries to remove every element that matches `target` but fails so because you're modifying the array. – Andreas Nov 09 '19 at 12:32
  • 1
    @Andreas it doesn't remove anything as the condition `i === a.length` is always false – ibrahim mahrir Nov 09 '19 at 12:33
  • @ibrahimmahrir Missed that part... But this at least prevents the corruption of the array^^ – Andreas Nov 09 '19 at 12:34
  • invert your `for` to do `i--` and to start from the `length - 1` element @ibrahimmahrir – DevFlamur Nov 09 '19 at 12:42
  • @DevFlamur but that will remove every matching element. OP wants to remove only the last one if it matches. – ibrahim mahrir Nov 09 '19 at 12:44
  • Does this answer your question? [Deleting array elements in JavaScript - delete vs splice](https://stackoverflow.com/questions/500606/deleting-array-elements-in-javascript-delete-vs-splice) – Andrei Nov 09 '19 at 12:55
  • @ibrahimmahrir then use `pop() ` look here https://alligator.io/js/push-pop-shift-unshift-array-methods/ – DevFlamur Nov 09 '19 at 12:55

3 Answers3

3

If it's the last element you're after then you don't need the loop at all, just check if the array is empty or not and access the last element directly:

function dedupeLast(a, target) {
   if(a.length && a[a.length - 1] === target){
      a.pop();
   }
}

It reads: if a is not empty (a.length != 0) and the last element a[a.length - 1] === target then, remove the last element using pop.

ibrahim mahrir
  • 29,774
  • 5
  • 43
  • 68
1

You can use pop, to access last element if it satisfies the criteria remove it else add it again.

function dedupeLast(a, target) {
  
  let temp = a.pop();
  if(temp === target){
    return;
  }
  else{
    a.push(temp);
  }
  
}
Akshay Bande
  • 2,332
  • 2
  • 10
  • 24
1

Since array.splice creates a new Array and copies the removed elements to it, I would use array.pop instead for better performance.

function dedupeLast(a, target) {
  let temp;
  if(a.length && a[a.length - 1] === target){
    temp = a.pop();
  }
}

Array.prototype.pop() just removes the last element an returns it. If you check before, if that element equals target, there is no need to pop and push. If you need the removed element for something else, you can just use temp.

Olafant
  • 809
  • 1
  • 7
  • 16