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});                                             
    }
}   
  • 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? – Chad Denaux May 7 at 2:00
  • Thanks for answer I used Array.include function. When loop working always result return false. – Hermes May 7 at 2:17
up vote 1 down vote accepted

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);

  • Thanks for answer but I shouldn't reduce $scope.result. Because I have to use another loops – Hermes May 7 at 2:15
  • @Hermes updated answer. It will not change your result. Check now. – VicJordan May 7 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 May 7 at 2:23
  • What's your expected output? – VicJordan May 7 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 May 7 at 2:30

Your Answer

 

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.