Home > Blockchain >  Sort desc if item is included in an array with lodash or with out
Sort desc if item is included in an array with lodash or with out

Time:06-11

I have a array of objects like so:

const attendList = [
{
  "first": "John",
  "last": "Foo",
  "uid": "-Lz8YxIYM_4L3f9nKM70",
},
{
  "first": "Jake",
  "last": "Foo",
  "uid": "-Lz8YxIYM_4L3fsdfM70",
}
...
]

Then I have an array containing the keys

const found = ["-Lz8YxIYM_4L3fsdfM70", "-Lz8YxIYM_4L3fsdf333", "-Lz8YxIYM_r4hfsdf333" ]

I want to sort attendList by placing the items that are in found at the bottom of the list. My incorrect attempt (using lodash) is:

let SetItemsLast = _.sortBy(attendList, ({uid}) => found.includes(uid) ? 0:1);

I'm obviously not doing it correctly. How can I resolve this?

CodePudding user response:

Try this if you need to keep the attendList items in order otherwise.

  let SetItemsLast = attendList.sort((a, b)=>{
    if(found.includes(a.uid)){
      return 1;
    }
    if(found.includes(b.uid)){
      return -1;
    }
    return 0;
  });

If you don't care whether the items at the bottom remain in order, you can just do this.

  let SetItemsLast = attendList.sort((a, b)=>{ return found.includes(b.uid) ? -1:0; });
  • Related