I have an array headings where I push elements:
for (let i = 1; i <= 13; i ) {
headings.push({
text: i,
type: "♠",
});
}
Now I want to remove for example the element [3,♠]
I tried with pop()
or something like that, but I can't find the way to do it.
CodePudding user response:
const idx = headings.findIndex(el => el.text === 3 && el.type === "♠")
headings.splice(idx,1)
CodePudding user response:
There are multiple ways to do it.
You can use filter
or splice
method to do it.
filter Here you can filter all other element then 3 and "♠" and assign it to new array.
findIndex
Here find index of your element and use splice
on array
let headings = [];
for (let i = 1; i <= 13; i ) {
headings.push({
text: i,
type: "♠",
});
};
let newHeadingsFilter = headings.filter(x => !(x.text === 3 && x.type == "♠"));
console.log(newHeadingsFilter);
let index = headings.findIndex(x => x.text == 3 && x.type == "♠");
headings.splice(index, 1);
console.log(headings);
CodePudding user response:
You can also use filter
const newHeadings = headings.filter(item => !item.type === "♠")
If you also want to check for the value of i
const newHeadings = headings.filter((item, index)=> !(item.type === "♠" && item.text == (index 1)))
This returns a new array and does not modify original
CodePudding user response:
Use lodash
's _.remove
:
const headings = [...Array(13).keys()].map(i => ({text: i 1, type: "♠"}));
_.remove(headings, {text: 3, type: "♠"});
console.log(headings);