I have a array that I'm moving a selected element to the top(like it's pinned), now I want to move it back where it was before in the list which I compare the IDs,
so want to show the pinned elements (that does have a key pinned:true
) to the top of array, and the ones that does not a key pinned: true
will be sorted by id.
All goes as desired, except when i want to show them as sorted by id which smaller ids will go to the top and greater will go after (1,2,3,4...)
Here is a sandbox where you can get a good idea of what's going on
https://codesandbox.io/s/serene-brattain-cro18?file=/src/App.tsx
const data = [
{ name: "Josef", id: 1 },
{ name: "Ali", id: 2 },
{ name: "Sheyda", id: 3 },
{ name: "Parviz", id: 4 },
{ name: "Victor", id: 5 },
{ name: "Mike", id: 6 },
{ name: "Ross", id: 7 },
{ name: "Chandler", id: 8 },
{ name: "Monica", id: 9 }
];
data.sort(function (x,y) {
return x.pinned === y.pinned ? 0 : x.pinned ? -1 : 1;
});
console.log(data)
So the point is I want the items with key pinned:true
to be at the first(which item get true
when i click on it and when I click back it gets false, and by default it's undefined) and the other with key pinned set to false
and undefined
will go under them and will be sorted by ids
Currently i am able to sort them as pinned:true
to the top and the other under them but I cannot sort the ones with false by IDs