Here is the object.
var arr = {
firstValue:"xyz",
content:[
{
"value": "abc",
"checked": true
},
{
"value": "xyz",
"checked": false
},
{
"value": "lmn",
"checked": true
}
]
}
In this firstValue is xyz so while mapping xyz should come first like this:
var arr = {
firstValue:"xyz",
content:[
{
"value": "xyz",
"checked": true
},
{
"value": "abc",
"checked": false
},
{
"value": "lmn",
"checked": true
}
]
}
How to achieve this by using javascript,
Thanks.
CodePudding user response:
const arr = {
firstValue: "xyz",
content: [
{
value: "abc",
checked: true,
},
{
value: "xyz",
checked: false,
},
{
value: "lmn",
checked: true,
},
],
};
const index = arr.content.findIndex((item) => item.value === arr.firstValue);
if (index !== -1 && index !== 0) {
arr.content.unshift(...arr.content.splice(index, 1));
}
CodePudding user response:
It looks like you just want to sort the matching object to the top.
You can either use Array#sort()
, though this will mutate the original object, so if it's in state you'll want to clone before sorting.
var arr = { firstValue: 'xyz', content: [ { value: 'abc', checked: true, }, { value: 'xyz', checked: false, }, { value: 'lmn', checked: true, }, ], };
const sorted = [...arr.content].sort((a, b) =>
(b.value === arr.firstValue) - (a.value === arr.firstValue));
console.log(sorted);
Otherwise you can find the index of the object using Array#findIndex()
and then use Array#splice()
and Array#unshift()
to move it to the beginning of the array. Here declaring a utility function and returning a copy of the passed array to avoid mutation.
var arr = { firstValue: 'xyz', content: [ { value: 'abc', checked: true, }, { value: 'xyz', checked: false, }, { value: 'lmn', checked: true, }, ], };
const orderFirst = (a) => {
const res = [...a];
const i = a.findIndex((o) => o.value === arr.firstValue);
if (i && i !== -1) {
res.unshift(res.splice(i, 1));
}
return res;
};
const sorted = orderFirst(arr.content);
console.log(sorted);