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
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 ;
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);