I have below piece of code, What I am trying to do is add a new record at the 0th position and then sort the array based on the label. But I can't get it to work; I am getting an empty array.
const array = [{id: '3', name: 'name1'},
{id: '4', name: 'name2'},
{id: '5', name: 'name3'}]
const items = array
.map((sp) => ({ label: sp.name, value: sp.id }))
.splice(0, 0, { label: '', value: '' })
.sort((a, b) => a.label - b.label);
console.log(items);
CodePudding user response:
Is this what you want?
const array = [
{ id: '3', name: 'name1' },
{ id: '4', name: 'name2' },
{ id: '5', name: 'name3' }
]
const items = array.map((sp) => ({ label: sp.name, value: sp.id }))
items.unshift({ label: '', value: ''})
items.sort((a, b) => a.value - b.value);
console.log(items);
Output:
[
{ label: '', value: '' },
{ label: 'name1', value: '3' },
{ label: 'name2', value: '4' },
{ label: 'name3', value: '5' }
]
Method unshift
here is used to add a new value at the beginning of the list. Both sort
and unshift
works in place therefore they do not return the modified array and update the existing variable instead.
CodePudding user response:
The error in this code is that the .splice() method returns an array containing the removed items, and does not modify the original array. So, the original array is not modified when .splice() is called on it. To fix this, you can assign the return value of .splice() to the original array:
const array = [{id: '3', name: 'name1'},
{id: '4', name: 'name2'},
{id: '5', name: 'name3'}]
const items = array
.map((sp) => ({ label: sp.name, value: sp.id }))
.splice(0, 0, { label: '', value: '' })
.sort((a, b) => a.label - b.label);
array = items;
console.log(array);