Scheinin
Scheinin

Reputation: 195

How to sort the values of an array according to the value of another array

list1 = [{name: 'apple'}, {name: 'pear'}, {name: 'banana'}]
list2 = ['banana', 'apple', 'pear']

expectation

list1 = [{name: 'banana'}, {name: 'apple'}, {name: 'pear'}]

How to make list2 and sort list1 through angularjs ng-repeat or JS

Upvotes: 0

Views: 68

Answers (5)

Manikant Gautam
Manikant Gautam

Reputation: 3591

Based on what you have and what you wannt to have . Here is how you get.

list1 = [{name: 'apple'}, {name: 'pear'},{name: 'banana'}];
list2 = ['banana', 'apple', 'pear'];
var result = [];
function getData(){
list2.forEach(function(e){
  let obj=list1.find(element=>element['name'] === e);
  result.push(obj);
})
console.log(result);
}
getData();
// In case you want to preserve with list1
list1.sort(function(a, b){  
  return list2.indexOf(a.name) - list2.indexOf(b.name);
});
console.log(list1)

Now you can use result as inside ng-repeat ;

Upvotes: 0

Harun Or Rashid
Harun Or Rashid

Reputation: 5927

Use a compare function as below :

var list1 = [{name: 'apple'}, {name: 'pear'}, {name: 'banana'}];
var list2 = ['banana', 'apple', 'pear'];

function comp(a, b) {
  return list2.indexOf(a.name) - list2.indexOf(b.name);
}

list1.sort(comp);

console.log(list1);

Upvotes: 0

Panos K
Panos K

Reputation: 1081

And a map solution

var list1=[{
  name: 'apple'
}, {
  name: 'pear'
}, {
  name: 'banana'
}];
var list2 = ['banana', 'apple', 'pear'];

list1 = list2.map(x=>{
return {name:x};
});

console.log(list1);

Upvotes: 1

Raghbendra Nayak
Raghbendra Nayak

Reputation: 1646

Try with this:

$scope.props = [{name: 'apple'}, {name: 'pear'}, {name: 'banana'}]

ng-repeat="prop in props | orderBy:'name'"

Upvotes: 0

Ankit Agarwal
Ankit Agarwal

Reputation: 30739

You can use the index of the array list2 to get the numeric values for sorting:

var list1 = [{
  name: 'apple'
}, {
  name: 'pear'
}, {
  name: 'banana'
}]
var list2 = ['banana', 'apple', 'pear'];
list1.sort(function(a, b) {
  return list2.indexOf(a.name) - list2.indexOf(b.name);
});
console.log(list1);

Upvotes: 0

Related Questions