I am trying to remove only items that were pushed into a list so that I am only left with the original list items
const list = ["a", "b", "c", "d"];
for (let i = 0; i < 4; i ) {
list.push(i);
}
console.log(list);
// outputs: a,b,c,d,1,2,3,4 // as expected
// how can we remove only the pushed items.
list.pop;
console.log(list);
// outputs : []
// desired output: a,b,c,d
CodePudding user response:
I'm not sure what your case is and why you want to extract the items from the array but anyway.
The first option would be: duplicating the array into another variable
or the second option: extracting it using splice when you know the length of the original array.
Snippets:
const list = ["a", "b", "c", "d"];
const original = list.slice(); // duplicating array
const originalLength = list.length // getting original length
for (let i = 0; i < 4; i ) {
list.push(i);
}
console.log("original1: ", original);
console.log("original2: ", list.slice(0, originalLength));
CodePudding user response:
You can remove the elements from the index where you have begun pushing new elements using splice.
const list = ["a", "b", "c", "d"];
for (let i = 0; i < 4; i ) {
list.push(i);
}
list.splice(list.length - 4)
console.log(list);
CodePudding user response:
If you need two to have one "for loop" pushing items into an array, and then remove those same items in another loop, then a simple solution would be
Snippet:
const list = ["a", "b", "c", "d"];
for (let i = 0; i < 4; i ) {
list.push(i);
}
for (let j of list) {
if (j) {
list.pop();
}
};
console.log(list);