Reputation: 71
I have this array
var a = [[1,3][2,3],[3,4],[6,7]];
var b =[[1,3],[2,3]];
I want to remove b array from a.
I tried it
var arr = [[1,3],[2,3]];
var b = [1,3];
var arr = arr.filter((el)=> !b.includes(el));
console.log(arr);
but it is returning the same array "arr". It's not removing the array "b" form array "arr".
Upvotes: 2
Views: 76
Reputation: 28455
In case of simplistic use case, where the order of items, number of items, value of items will be same you can try following
var a = [[1,3], [2,3]];
var b =[1,3];
a = a.filter(v=> v.join() !== b.join());
console.log(a);
If you want to consider order, number and value, please try following
var a = [[1,3], [2,3]];
var b =[1,3];
// Create a map where key is item and value is its occurence
let bObj = b.reduce((ac, c) => Object.assign(ac, {[c]: (ac[c] || 0) + 1}), {});
a = a.filter(v=> {
// For every value, create a copy of bObj
let temp = {...bObj};
// for every value in item, decrements the value by 1
v.forEach(e => temp[e] = (temp[e] || 0) - 1);
// Get all the values of object
let tempValues = Object.values(temp);
// If all values are 0, then it is an exact match, return false else return true
if(new Set(tempValues).size === 1 && tempValues[0] === 0) return false;
return true;
});
console.log(a);
EDIT
var a = [[1,3],[2,3],[3,4],[6,7]];
var b = [[1,3],[2,3]];
// Create a map where key is item and value is its occurence
let bObj = b.map(v => v.reduce((ac, c) => Object.assign(ac, {[c]: (ac[c] || 0) + 1}), {}));
a = a.filter(v=> {
// For every value, create a copy of bObj
let temp = JSON.parse(JSON.stringify(bObj));
// for every value in item, decrements the value by 1
v.forEach(e => temp.forEach(t => t[e] = (t[e] || 0) - 1));
return !temp.some(t => {
// Get all the values of object
let tempValues = Object.values(t);
// If all values are 0, then it is an exact match, return false else return true
return (new Set(tempValues).size === 1 && tempValues[0] === 0)
});
});
console.log(a);
Upvotes: 4
Reputation: 41
var my_array = ["raj","bob","clreak","kevin","dJ"];
var start_index = 0
var number_of_elements_to_remove = 1;
var removed_elements = my_array.splice(start_index, number_of_elements_to_remove);
Upvotes: 0
Reputation: 30739
You can first find the index
on arr
that you want to remove using every()
operation then splice()
it:
var arr = [[1,3],[2,3]];
var b = [1,3];
var index = arr.findIndex(item => item.every(elem => b.includes(elem)));
arr.splice(index,1);
console.log(arr);
Upvotes: 0
Reputation: 386604
You could search fr the index by stringify the inner array and check against the strigified array b
. Then check the index and splice.
var a = [[1, 3], [2, 3]],
b = [1, 3],
index = a.findIndex(
(json => inner => JSON.stringify(inner) === json)
(JSON.stringify(b))
);
if (index !== -1) {
a.splice(index, 1);
}
console.log(a);
Upvotes: 0