lunacafu
lunacafu

Reputation: 366

filter array of objects with underscore and get new array of values

I do have an array of objects and I want to create a filter function to return an new array

var items = [{
        "row": 0,
        "column": 0,
        "items": [2, 3, 4, 5, 6, 7]
    }, {
        "row": 0,
        "column": 1,
        "items": [8, 9, 10, 11, 12, 13]
            ....



        {
            "row": 2,
            "column": 2,
            "items": [50, 51, 52, 53, 54, 55]
        }]

    var newArray = function (items, row) {
        //filter items and return new array

        return filtered
    }

newArray should contain all values from 'items' that have the same row value.

Upvotes: 0

Views: 4354

Answers (3)

Bergi
Bergi

Reputation: 664434

Maybe you're looking for this:

_.reduce(items, function(res, item) {
    var key = item.row;
    if (!(key in res)) res[key] = [];
    [].push.apply(res[key], item.items);
    return res;
}, {})

Upvotes: 2

broofa
broofa

Reputation: 38122

In underscore, to get all items where the row value matches the index of the item in the array:

var items = [...];
var filteredItems = _.filter(items, function(item, i) {
  return item.row == i;
});

Or with the native Array.prototype.map method. E.g.

var items = [...];
var filteredItems = items.filter(function(item, i) {
  return item.row == i;
});

Upvotes: 1

Jon
Jon

Reputation: 437366

If I understand the question correctly, the result would be given by

function filter(items, row) {
    return _.chain(items)    // initiate method chaining for convenience
        .where({row: row})   // filter out objects from rows we don't care about
        .pluck("items")      // get the "items" arrays from the filtered objects
        .flatten()           // concatenate them into a single array
        .value();            // unwrap the result to return it
}

Calling filter(items, 0) in the example given would return

[2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]

which is the concatenated aggregate of items arrays inside objects with row equal to 0.

Upvotes: 3

Related Questions