简体   繁体   中英

TS 2 arrays, if item from first array exists in second array then append to start of second array

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"}
]

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

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>

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM