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
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);
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);
Try with this:
$scope.props = [{name: 'apple'}, {name: 'pear'}, {name: 'banana'}]
ng-repeat="prop in props | orderBy:'name'"
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
;
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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.