2

I created an array is empty. I want to push unique object. I want to use for loop. But firstly array length is zero. So doesnt work for loop. How can I do?

$scope.arr=[]; $scope.result=[ {category: "Home", categoryInt: 1, categoryPercent:50}, {category: "Office", categoryInt: 1, categoryPercent:25}, {category: "Office", categoryInt: 1, categoryPercent:25}, {category: "Office", categoryInt: 1, categoryPercent:25} [ for(var z=0; z<$scope.arr.length; z++){ if ($scope.arr[z].percent === $scope.result[a].categoryPercent) { return; } else { $scope.arr.push({category: $scope.result[a].category, percent: $scope.result[a].categoryPercent, categoryInt: $scope.result[a].categoryInt}); } } 
2
  • Can you not declare the object in question as a variable and then use the Array.include() function as a check in a conditional statement?CommentedMay 7, 2018 at 2:00
  • Thanks for answer I used Array.include function. When loop working always result return false.
    – Hermes
    CommentedMay 7, 2018 at 2:17

1 Answer 1

1

Use Array.reduce() to have array of object of unique objects. Below is working code:

let arr = []; var result = [{category:"Home",categoryInt:1,categoryPercent:50},{category:"Office",categoryInt:1,categoryPercent:25},{category:"Office",categoryInt:1,categoryPercent:25},{category:"Office",categoryInt:1,categoryPercent:25}]; arr = Object.values(result.reduce((acc, cur) => Object.assign(acc, { [cur.categoryPercent]: cur }), {})); console.log(arr);

5
  • Thanks for answer but I shouldn't reduce $scope.result. Because I have to use another loops
    – Hermes
    CommentedMay 7, 2018 at 2:15
  • @Hermes updated answer. It will not change your result. Check now.CommentedMay 7, 2018 at 2:16
  • Thats worked but doesnt work perfectly. Some values is repeated. How can I use multi filter? For example I want to use categoryPercent and categoryInt
    – Hermes
    CommentedMay 7, 2018 at 2:23
  • What's your expected output?CommentedMay 7, 2018 at 2:25
  • Your answer is correct but. $scope.result has more than property. I have written some property. When I use your code some values pushed to $scope.arr. So I think I have to use multi filter for example arr = Object.values(result.reduce((acc, cur) => Object.assign(acc, { [cur.categoryPercent, cur.categoryInt ]: cur }), {}));
    – Hermes
    CommentedMay 7, 2018 at 2:30

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.