Reputation: 226
I have 2 arrays in javascript
Array 1
var columns=[{name: 'id', default: true}, {name: 'type', default: true},{name: 'typeName', default: true}, {name: 'client', default: false}];
Array 2
var unSelect=["id", "type", "typeName"]
Now I want a new array i.e Array 3
where only non-matching element matches
i.e name
of column
In this case
var array 3=[{name: 'client', default: false}]
I have tried to splice, but my index is not matching.
Upvotes: 0
Views: 82
Reputation: 26161
This would be my solution with Array.prototype.filter()
& Array.prototype.some()
combo.
var columns = [{name: 'id', default: true}, {name: 'type', default: true},{name: 'typeName', default: true}, {name: 'client', default: false}],
unSelect = ["id", "type", "typeName"],
filtered = columns.filter(f => !unSelect.some(e => e == f.name));
console.log(filtered);
Upvotes: 0
Reputation: 386550
You could use a hash table as a reference for not wanted item for faster access than indexOf
.
var columns = [{ name: 'id', default: true }, { name: 'type', default: true }, { name: 'typeName', default: true }, { name: 'client', default: false }],
unSelect = ["id", "type", "typeName"],
hash = Object.create(null),
result;
unSelect.forEach(function (a) {
hash[a] = true;
});
result = columns.filter(function (a) {
return !hash[a.name];
});
console.log(result);
Upvotes: 0
Reputation: 23778
Here is the simplest way to do it using Array.prototype.map
function. This function can iterate an array and return what you want per every iteration.
var array3 = columns.map(function(item) {
if (unselected.indexOf(item.name) < 0) //see if the name of an element object is in the unselected array
return item; // if yes, return the element
})
Upvotes: 1
Reputation: 68393
try using filter as
var unSelect=["id", "type", "typeName"];
var array3 = columns.filter(function(obj){
return unSelect.indexOf( obj.name ) == -1;
});
DEMO
var columns = [{
name: 'id',
default: true
}, {
name: 'type',
default: true
}, {
name: 'typeName',
default: true
}, {
name: 'client',
default: false
}];
var unSelect = ["id", "type", "typeName"];
var array3 = columns.filter(function(obj) {
return unSelect.indexOf(obj.name) == -1;
});
console.log(array3);
Upvotes: 0