Reputation: 195
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
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
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
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
Reputation: 1646
Try with this:
$scope.props = [{name: 'apple'}, {name: 'pear'}, {name: 'banana'}]
ng-repeat="prop in props | orderBy:'name'"
Upvotes: 0
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