0

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.

asked Jun 15, 2016 at 10:07

4 Answers 4

1

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 
})
answered Jun 15, 2016 at 10:13
Sign up to request clarification or add additional context in comments.

Comments

0

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);

answered Jun 15, 2016 at 10:09

Comments

0

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);

answered Jun 15, 2016 at 10:14

Comments

0

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);

answered Jun 15, 2016 at 10:29

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.