2

I have an array that has a bunch of ids

var arr = ["562f464a9cdf7e6e33aa2514","562f464a9cdf7e6e33aa2514"];

and I have an array of objects that looks somewhat like this

[{
    "boatId": "562f464a9cdf7e6e33aa2514",
        "canPoll": true,
}, {
    "boatId": "562f4647e6e33aa2514",
        "canPoll": true,
}]

I want to pluck out the objects from the second list whose ids are not in the array arr

I came up with the following line but it returns false;

var finalBoats = _.map(boats, function (boat) {
    if (originalBoats.length > 0) {
        _.each(originalBoats, function (originalBoat) {
            if (originalBoat === boat.boatId) {
                return boat;
            }
        });
    } else {
        return boat;
    }
});

I also have to account for times that the first array might be empty.

Not sure how I can do this in underscore.

Update : Here is what I want to do exactly

var arr = ["1","2"];

   var unfilteredBoats = [{
        "boatId": "3",
            "canPoll": true,
    }, {
        "boatId": "2",
            "canPoll": true,
    }]

so the extracted array of elements should be

[{
        "boatId": "3",
            "canPoll": true,
    }]

also if arr is empty, it shouldn't filter at all, that part is rather simple.

0

1 Answer 1

4

You can use filter in VanillaJS

var filteredArr = originalBoats.filter(function(e) {
    return arr.indexOf(e.boatId) === -1;
});

Same can be done using underscore's filter and contains

var filteredArr = _.filter(originalBoats, function(el) {
    return _.contains(arr, el.boatId) === false;
});

Demo

var arr = ["1", "2"];

var unfilteredBoats = [{
  "boatId": "3",
  "canPoll": true,
}, {
  "boatId": "2",
  "canPoll": true,
}];

var filteredArr = unfilteredBoats.filter(function(e) {
  return arr.indexOf(e.boatId) === -1;
});

console.log(filteredArr);

document.getElementById('result').innerHTML = JSON.stringify(filteredArr, 0, 4);
<pre id="result"></pre>

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

4 Comments

Thanks, my goal is to extract the elements from the arr array that are not present in originalBoats
@Bazinga777 Can you please add an example of both the arrays, I think the above should work.
@Bazinga777 I've added demo, please check
You are a life saver. That worked well. Didn't know about the filter property. Thanks

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.