Reputation: 13206
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);
}
}
}
Upvotes: 1
Views: 1682
Reputation: 828
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.
Upvotes: 1
Reputation: 31682
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
.
Upvotes: 3
Reputation: 2587
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);
}
}
Upvotes: 1