I need to replace last element in array.
I know, that I can use filter
method to replace element, but how to replace the latest element?
How do I know the index of element?
Should I check size of array and replace latest element?
or maybe remove latest element and add new?
Generally i'm adding elements using unshift:
this.array.unshift({
name: cmd.event.type,
id: cmd.event.id,
xpath: cmd.event.xpath,
x: `x: ${xparam}`,
y: `y: ${yparam}`,
})
and what should I do to replace latest this.array
element?
I need to replace last element in array.
I know, that I can use filter
method to replace element, but how to replace the latest element?
How do I know the index of element?
Should I check size of array and replace latest element?
or maybe remove latest element and add new?
Generally i'm adding elements using unshift:
this.array.unshift({
name: cmd.event.type,
id: cmd.event.id,
xpath: cmd.event.xpath,
x: `x: ${xparam}`,
y: `y: ${yparam}`,
})
and what should I do to replace latest this.array
element?
-
4
this.array[this.array.length - 1] = /* Whatever you want */
– Guerric P Commented May 25, 2021 at 20:07 - 1 @GuerricP in Vue 2 this is not reactive – Boussadjra Brahim Commented May 25, 2021 at 20:14
3 Answers
Reset to default 4Try to use splice
method :
this.array.splice(this.array.length - 1, 1, {
name: cmd.event.type,
id: cmd.event.id,
xpath: cmd.event.xpath,
x: `x: ${xparam}`,
y: `y: ${yparam}`,
})
the 1st param : the element index to be replaced
2nd param: the delete count
3rd param : your new element to insert
for Vue 2 you could use this.$set
method :
this.$set(this.array,this.array.length - 1,{
name: cmd.event.type,
id: cmd.event.id,
xpath: cmd.event.xpath,
x: `x: ${xparam}`,
y: `y: ${yparam}`,
})
You could get latest element index with length
property
const latestElement = this.array[this.array.length - 1]
using index is IMHO more readable than splice when replacing the last item
this.array[this.array.length - 1] = {
...item props...
};
maybe pop&push is even nicer
this.array.pop()
this.array.push({
...item props...
});
enter code here
but you wrote that you are adding items using unshift, which adds to beginning of array, so if you ment "latest" as "latest added by unshift", then replacing is just
this.array[0] = {
...item props...
};
or just remove latest added
this.array.shift();
as it removes forst element in array