Answer the question
In order to leave comments, you need to log in
Why does the unshift method not work correctly?
I want to add a post to the beginning of the list, but then the id after adding the second element is not considered, that is, + 1 is not added to the post id. Also when I delete, all elements added after the first are deleted at once. When I add via push, everything works fine. Through unshift or splice, this problem occurs, help to solve and understand why this is happening
Method:
addPost(title: string, url: string): void {
const id: number = this.collection.length
? this.collection[this.collection.length - 1].id + 1
: 1;
const post: Picture = {
title,
url,
id
};
this.collection.unshift(post);
}
Answer the question
In order to leave comments, you need to log in
You add elements to the beginning of the array and calculate the new id based on the last element. Obviously, no matter how many elements you add in this way, the id of the last one will not change, which means that the new id will be the same. If I were you, instead of jumping from a specific element, I would look for the maximum id:
const id = Math.max(0, ...this.collection.map(n => n.id)) + 1;
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question