Reputation: 462
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});
}
}
Upvotes: 2
Views: 979
Reputation: 21776
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);
Upvotes: 1