Home > other >  Issue when trying to sort array?
Issue when trying to sort array?

Time:11-04

        // const first = data.groups_with_selected[7];
        // const second = data.groups_with_selected[20];
        // data.groups_with_selected.splice(2, 0, first, second);
        // data.groups_with_selected.splice(9, 1)
        // data.groups_with_selected.splice(21, 1)

But Issue with the above code is that, I am able to get the updated sorted console value in the console. But filters wise it's not updating.

CodePudding user response:

the solution for this problem is by grouping the array first, then use flat() to flatten/restore it so it have the same level:

const orderMap = ['third', 'second', 'first'];

const array = [{name: 'first'}, {name: 'second'}, {name: 'third'}, {name: 'second'}];

const sorted = orderMap.reduce((prev, curr, index) => {
prev[index] = array.filter(item => item.name === curr)
return prev
}, []).flat()

console.log(sorted)
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

Using the sort javascript method. Since is an Object you are not sorting directly the value. Inside the groups method, using your sorted variable. This would sort the array using the "name" as the sort key alphabetically.

sorted.sort((a, b) => {
    return a.name.toLocaleLowerCase().localeCompare(b.name.toLowerCase());
})

return sorted
  • Related