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.

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

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

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

Comments

Your Answer

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.