devC
devC

Reputation: 1444

Filter an array and create a new array

I have a very simple requirement for filter some objects from a larger array and create a sub-array. Right now, I'm doing it as follows, but I'm wondering whether I could do inline and avoid the for-each.

        var branches = $filter('filter')(vm.locations, { 'fkLocationTypeId': 5 });
        vm.branchList = [];
        angular.forEach(branches, function (obj) {
            vm.branchList.push({ id: obj.Id,  label: obj.locationDisplayName });
        });

Upvotes: 0

Views: 110

Answers (2)

user3297291
user3297291

Reputation: 23372

I don't think there's much wrong with your use of forEach, but you could replace it by a map operation on the filtered set.

Personally, I'd use reduce to combine both filter and map operations in one loop, but you'd probably only start seeing a performance increase when you're filtering very large sets of data.

To combine the two in one reducer:

const locToObj = loc => 
  ({ id: loc.Id,  label: loc.locationDisplayName });
 
const branchReducer = (acc, loc) =>
  loc.fkLocationTypeId === 5
    ? (acc.push(locToObj(loc)), acc)
    : acc
 
const branches = vm.locations.reduce(branchReducer, []);
    

Upvotes: 2

Lennholm
Lennholm

Reputation: 7480

Since you want to both filter the array and modify the retained items, you can use filter() in combination with map(), both native array methods

vm.branchList = vm.locations
  .filter(function(location) {
    return location.fkLocationTypeId === 5;
  })
  .map(function(location) {
    return {
      id: location.Id,
      label: location.locationDisplayName
    };
  });

If you want to avoid iterating over the array twice you can use the reduce() method to perform both the filtering and mapping at the same time

vm.branchList = vm.locations
  .reduce(function(builtList, location) {
    if (location.fkLocationTypeId === 5) {
      return builtList.concat({
        id: location.Id,
        label: location.locationDisplayName
      });
    }
    return builtList;
  }, []);

Upvotes: 2

Related Questions