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? Commented May 7, 2018 at 2:00
  • Thanks for answer I used Array.include function. When loop working always result return false. Commented May 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);

Sign up to request clarification or add additional context in comments.

5 Comments

Thanks for answer but I shouldn't reduce $scope.result. Because I have to use another loops
@Hermes updated answer. It will not change your result. Check now.
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
What's your expected output?
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 }), {}));

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.