Nicholas Hazel Nicholas Hazel -5 years ago 89
jQuery Question

Filter selections from JSON in Angular based on array of values

So my data-set looks like this (much more stats behind it but lets keep this simple):

$scope.peopleData = [
{"name": "Name1", "img": "name1Img.png"},
{"name": "Name2", "img": "name2Img.png"}...

Doing just fine displaying all of the items via a simple:

<div ng-repeat="person in peopleData">
<img src="img/people/{{person.img}}" alt="{{}}" />

Now let's say I'm storing friends and have a different section that only lists specific people. Take, for example, an array such as:

var friends = ["Name4", "Name9"];

How would I go about writing a function that would return:

$scope.friends = [
{"name": "Name4", "img": "name4Img.png"},
{"name": "Name9", "img": "name9Img.png"}...

Essentially, I want to search through all of the peopleData and return a smaller array based upon several values contained within an array?

Surely there has to be a simple method to use .filter() to find multiple strings as acceptable values?

$scope.friendData = peopleData.filter(friends);

I think I'm just missing a small piece here...

Answer Source

Use Array#filter with Array#indeOf to test the value in array

var friends = [{
  "name": "Name4",
  "img": "name4Img.png"
}, {
  "name": "Name9",
  "img": "name9Img.png"
}, {
  "name": "Name10",
  "img": "name10Img.png"
var friendsArr = ["Name4", "Name9"];
var friendData = friends.filter(function(item) {
  return friendsArr.indexOf( !== -1; //`` exists in `friendsArr`

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download