Haradzieniec Haradzieniec - 6 months ago 42
AngularJS Question

AngularJS: use filter to split array into arrays

There is an array of objects that I would like to split into several arrays.
These strings work perfect in AngularJS and split the whole array

arr
into four arrays the way I want:

var arr0 = $filter('filter')(arr, { filterVal: 0 }, true);
var arr1 = $filter('filter')(arr, { filterVal: 10 }, true);
var arr2 = $filter('filter')(arr, { filterVal: 50 }, true);
var arr3 = $filter('filter')(arr, { filterVal: 60 }, true);


Actually, the four arrays above total are the original array (because
filterVal
in each item is always equal to
0, 10, 50 or 60
).

So, the question is how to make the code above shorter? So, I need to split
arr
into new_arr in one line so that

new_arr[0] is equal to arr0,
new_arr[1] is equal to arr1,
new_arr[2] is equal to arr2,
new_arr[3] is equal to arr3.


With another words, I would like to use one string of code (if possible) instead of four strings. Is it possible with AngularJS?

This way I would make it more dynamic (not stick to four).

Thank you.

Just added:
As example,

arr = [
{"code":"kfk", "flag":"dfmk", "filterVal": 0},
{"code":"asg", "flag":"sdg3", "filterVal": 50},
{"code":"asdf", "flag":"34t", "filterVal": 10},
{"code":"hsdfh", "flag":"dfsg43", "filterVal": 50},
];


is expected to be conferted into

var new_arr[0] = [{"code":"kfk", "flag":"dfmk", "filterVal": 0}];//0s
var new_arr[1]= [{"code":"asdf", "flag":"34t", "filterVal": 10},];//10s
var new_arr[2]= [{"code":"asg", "flag":"sdg3", "filterVal": 50},{"code":"hsdfh", "flag":"dfsg43", "filterVal": 50}];//50s
var new_arr[3]= [];//60s

Answer

You could use plain Javascript and an array for the grouping.

var array = [{ "code": "kfk", "flag": "dfmk", "filterVal": 0 }, { "code": "asg", "flag": "sdg3", "filterVal": 50 }, { "code": "asdf", "flag": "34t", "filterVal": 10 }, { "code": "hsdfh", "flag": "dfsg43", "filterVal": 50 }, ],
    groups = [{ filterVal: 0 }, { filterVal: 10 }, { filterVal: 50 }, { filterVal: 60 }],
    result = groups.map(function (a) { return []; });

array.forEach(function (a) {
    groups.some(function (b, i) {
        var k = Object.keys(b)[0];
        return a[k] === b[k] && result[i].push(a);
    });
});

console.log(result);

Or you could use a more linear approach

var array = [{ "code": "kfk", "flag": "dfmk", "filterVal": 0 }, { "code": "asg", "flag": "sdg3", "filterVal": 50 }, { "code": "asdf", "flag": "34t", "filterVal": 10 }, { "code": "hsdfh", "flag": "dfsg43", "filterVal": 50 }, ],
    filter = [{ filterVal: 0 }, { filterVal: 10 }, { filterVal: 50 }, { filterVal: 60 }],
    groups = Object.create(null),
    result = filter.map(function (a) { return []; });

filter.forEach(function (b, i) {
    groups[b[Object.keys(b)[0]]] = i;
});
array.forEach(function (a) {
    result[groups[a.filterVal]].push(a);
});

console.log(result);