Home > Blockchain >  How can i use the AngulsJS functions to simplify a for loop?
How can i use the AngulsJS functions to simplify a for loop?

Time:07-13

I have the following loop and was wondering if there is a more efficient way of doing this in AngularJS. So i want to loop through each item in ListA and if it doesnt exist in ListB then i want to push the item from ListA into ListB. But the break; stops the loop , it doesnt go through all items in ListA

                    for (item of $scope.ListA) {
                    let found = false;
                    for (obj of $scope.ListB) {
                        if (obj.Name == item.Name
                            && obj.Field == item.Field
                            && obj.DisplayName == item.DisplayName)
                        {
                            found = true;
                     //       console.log("double found !");
                            break;
                        }
                    }
                    if (!found)
                        $scope.ListB.push(newObj);
                }

How can i do this using AngularJS functions ?

CodePudding user response:

I don't know if there is any specific angularjs functionality, but assuming that ListA and ListB just javascript arrays, you can use standard array methods to simplify your solution.

For example, here I use array.filter, array.some and ... spread operator:

// Scope example
const $scope = {
  ListA: [
    { Name: 'name1', Field: 'field1', DisplayName: 'displayName1' },
    { Name: 'name2', Field: 'field2', DisplayName: 'displayName2' },
    { Name: 'name3', Field: 'field3', DisplayName: 'displayName3' },
  ],
  ListB: [
    { Name: 'name2', Field: 'field2', DisplayName: 'displayName2' },
    { Name: 'name4', Field: 'field4', DisplayName: 'displayName4' },
  ],
};

// A function that checks if a list contains an item
const hasItemInList = (item, list) => {
  // Here we use "array.some" method, which returns "true" if condition is true for any of the array items
  return list.some(listItem => 
    listItem.Name == item.Name &&
    listItem.Field == item.Field &&
    listItem.DisplayName == item.DisplayName
  );
}

// Getting the array of items that should be added to the listB,
// Here we use "array.filter" to filter the items of array by provided condition
const itemsToAdd = $scope.ListA.filter(item => !hasItemInList(item, $scope.ListB));

// And here we push all the items to the listB,
// we use a spread operator "..." here to push all the items of array at once
$scope.ListB.push(...itemsToAdd);

console.log($scope.ListB);

Array methods - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array

  • Related