0
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

0

5 Answers 5

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

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 ;

1 Comment

@Scheinin glad to help.
0

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

1 Comment

@Scheinin glad to help
0

Try with this:

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

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.