Reputation: 1251
In Angular, I have an array like this:
$scope.colors =["blue","red","pink","yellow"];
And another object
$scope.cars=[{"brand":"Ford","color":"blue"},{"brand":"Ferrari","color":"red"},{"brand":"Rolls","color":"blue"}];
I would like to do filter, so that
<ul>
<li ng-repeat="n in colors | filter:colorFilter">
</li>
</ul>
The ng-repeat would just display the elements in the $scope.colors
that exist as values in the $scope.cars
So, in other words, it would just display blue and red
Thanks in advance!
Upvotes: 1
Views: 619
Reputation: 13356
Given colors and cars arrays, you can filter colors by:
var colors =["blue","red","pink","yellow"];
var cars=[ {"brand":"Ford","color":"blue"},{"brand":"Ferrari","color":"red"},{"brand":"Rolls","color":"blue"}];
var filteredColors = colors.filter(color => cars.some(car => car.color === color));
console.log(filteredColors);
If you cannot use ES6, it should be:
var colors =["blue","red","pink","yellow"];
var cars=[ {"brand":"Ford","color":"blue"},{"brand":"Ferrari","color":"red"},{"brand":"Rolls","color":"blue"}];
var filteredColors = colors.filter(function(color) {
return cars.some(function(car) {
return car.color === color;
});
});
console.log(filteredColors);
Upvotes: 1
Reputation: 48437
You can use map
method which accepts as parameter a callback function in order to obtain all the colours from each car item from $scope.cars
, and then use Set
constructor in order to find out unique
colours. Then you have to use a filter
function.
Then you have to use a filter
function.
let colors =["blue","red","pink","yellow"];
let cars = [{"brand":"Ford","color":"blue"},{"brand":"Ferrari","color":"red"},{"brand":"Rolls","color":"blue"}];
let uniqueColours= [...new Set(cars.map(c => c.color))];
const filteredColors = colors.filter(a=>uniqueColours.includes(a));
console.log(filteredColors);
You can do this in a single line:
const colors =["blue","red","pink","yellow"],cars = [{"brand":"Ford","color":"blue"},{"brand":"Ferrari","color":"red"},{"brand":"Rolls","color":"blue"}],
filteredColors = colors.filter(a => cars.map(a => a.color).includes(a));
console.log(filteredColors);
Without arrow functions.
const colors =["blue","red","pink","yellow"],cars = [{"brand":"Ford","color":"blue"},{"brand":"Ferrari","color":"red"},{"brand":"Rolls","color":"blue"}],
filteredColors = colors.filter(function(a){
return cars.map(function(c){
return c.color;
}).includes(a)});
console.log(filteredColors);
Upvotes: 1