Remove element from Array of Arrays
I have a array of arrays like the following:
myArray = [
["ooooh", "that"],
["dog ", "of"],
["mine", "word...."]
]
I now wish to delete the array item: ["ooooh", "that"]
Assuming that I know element 0 is "ooooh"
and element 1 is "that"
, but i do not know the element's position within the enclosing array, can this be achieved efficiently?
The general responses from my research seem to be saying delete myArray['1']
, or know the number of the element in the array- in my case in need both element 0 & 1 to match for removal.
In pseudo code i would like:
myArray.destroy(["ooooh", "that"])
How can this be achieved?
You can use splice
to remove an item out of the list.
myList.splice(
myList.findIndex( item =>
item[0] == "ooooh" && item[1] == "that"
),
1);
Hope this helps :>
myList = [
["ooooh", "that"],
["dog ", "of"],
["mine", "word...."]];
myList.splice(myList.findIndex(item => item[0] == "ooooh" && item[1] == "that"), 1);
console.log(myList)
Well there are several ways of doing this as the other answers pointed out, but I think the simplest way is to use filter. Like this::
myList = [
["ooooh", "that"],
["dog ", "of"],
["mine", "word"]
];
myList = myList.filter((element)=>
//filter condition
(!
((element[0] == 'ooooh') && (element[1] == 'that'))
)
);
console.log(myList)
Just filter your array
var myList = [
["ooooh", "that"],
["dog ", "of"],
["mine", "word...."]
]
deleteFromList = (val, list) => list.filter(a=>JSON.stringify(a)!=JSON.stringify(val))
console.log(
deleteFromList(["ooooh", "that"], myList)
)
/* Same as */
myList = myList.filter(a=>JSON.stringify(a)!=JSON.stringify(["ooooh", "that"]))
console.log(myList)
You can use the filter function comparing arrays as strings
myList = [
["ooooh", "that"],
["dog ", "of"],
["mine", "word...."]
];
let findMe = ["ooooh", "that"]
myList = myList.filter((curr) => curr.join() !== findMe.join())
console.log(myList)