1

I have 2 arrays of objects exclude and people, I want to create a new object by checking exclude properties against people properties and only adding objects in people that don't feature in exclude. So far my attempt is a little wild and wondering if someone can help make things a little better or offer a nicer solution?

Fiddle http://jsfiddle.net/kyllle/k02jw2j0/

JS

var exclude = [{
    id: 1,
    name: 'John'
}];

var peopleArr = [{
    id: 1,
    name: 'John'
}, {
    id: 2,
    name: 'James'
}, {
    id: 3,
    name: 'Simon'
}];

var myObj = [];
for (key in peopleArr) {
    for (k in exclude) {

        if (JSON.stringify(peopleArr[key]) != JSON.stringify(exclude[k])) {

            console.log(peopleArr[key]);
            myObj.push(peopleArr[key]);

        }
    }
}

console.log(myObj);

3 Answers 3

1

Under the assumption that exclude can have multiple items, I would use a combination of filter() and forEach() :

var newArray = peopleArr.filter(function(person) {
    include = true;
    exclude.forEach(function(exl) {
        if (JSON.stringify(exl) == JSON.stringify(person)) {
            include = false;
            return;
        }
    })
    if (include) return person;
})

forked fiddle -> http://jsfiddle.net/6c24rte8/

Sign up to request clarification or add additional context in comments.

Comments

1

You repeat some JSON.stringify calls.
You can convert your arrays to JSON once, and then reuse it. Also, you can replace your push by Array.prototype.filter.

var excludeJson = exclude.map(JSON.stringify);

peopleArr = peopleArr.filter(function(x) { 
    return excludeJson.indexOf(JSON.stringify(x)) === -1;
});

Here is the working snippet:

var exclude = [{
    id: 1,
    name: 'John'
}];

var peopleArr = [{
    id: 1,
    name: 'John'
}, {
    id: 2,
    name: 'James'
}, {
    id: 3,
    name: 'Simon'
}];

var excludeJson = exclude.map(JSON.stringify);

peopleArr = peopleArr.filter(function(x) { 
  return excludeJson.indexOf(JSON.stringify(x)) === -1;
});

document.body.innerText = JSON.stringify(peopleArr);

Comments

1

This can be achieved with .filter and .findIndex

var myObj = peopleArr.filter(function(person){
   var idx = exclude.findIndex(function(exc) { return person.id == exc.id && person.name == exc.name; });
   return idx == -1; // means current person not found in the exclude list
});

I have explicitly compared the actual properties back to the original, there is nothing particularly wrong with your original way of comparing the stringified version (JSON.stringify(e) == JSON.stringify(x) could be used in my example)

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.