3

I have 2 lists of objects.

One is the list of 'all' objects, the second is the list of 'special' objects.

The first list contains all objects, including special objects.

How do I sort my list of 'all' objects, to order the objects in the following fashion: First 'special' objects, and then all the rest of the objects?

Each object has an id.

For example,

List 1:

[
  {Id: 1, Name: "a", Surname: "a"},
  {Id: 2, Name:"b", Surname:"b"},
  {Id: 3, Name: "c", Surname: "c"}
]

List 2:

[
  {Id: 2, Name:"b", Surname:"b"}
]

How do I order it, so the final list is:

[
  {Id: 2, Name:"b", Surname:"b"},
  {Id: 1, Name: "a", Surname: "a"},
  {Id: 3, Name: "c", Surname: "c"}
]

2 Answers 2

3

You can use the find function to check if one of the two compared elements are special and return the result accordingly in a custom sort function:

let all = [{Id: 1, Name: "a", Surname: "a"}, {Id: 2, Name:"b", Surname:"b"}, {Id: 3, Name: "c", Surname: "c"}];

let special = [{Id: 2, Name:"b", Surname:"b"}];

function sortFunc(a, b) {
  var s1 = special.find(s=>s.Id==a.Id);
  var s2 = special.find(s=>s.Id==b.Id);
  if(s1 && s2) return 0;
  else if(s1) return -1;
  else if(s2) return 1;
  return 0;
}

let sorted = all.slice().sort(sortFunc);

console.log(sorted);

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

1 Comment

I would also add that .sort() method is implemented in a mutable way and will change original array. So you probably would like to use .slice() before hand like that let sorted = all.slice().sort(sortFunc);
0

If you are willing to include lodash you can get the result with this

const List1 = [
  {Id: 1, Name: "a", Surname: "a"}, 
  {Id: 2, Name:"b", Surname:"b"}, 
  {Id: 3, Name: "c", Surname: "c"}
]
const List2 = [
  {Id: 2, Name:"b", Surname:"b"}
]

const SpecialIds = _.map(List2, (v) => { return v.Id })

const List3 = _.sortBy(_.map(List1, (v) => { 
  return _.merge({}, v, { 
    ...v, 
    Type: _.indexOf(SpecialIds, v.Id) === -1 ? '1_Normal' : '0_Special' 
  })
}), ['Type', 'Id'])   


console.log(List3)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>

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.