1๐
โ
You dont need to sort the complete array if you just want to move the element to the start and do not care about the order of other elements.
You can simply find the index of the element and swap it with the first one.
const a = [{
"iso2": "KH",
"countryName": "Cambodia",
"nationality": "Cambodian"
},
{
"iso2": "KI",
"countryName": "Kiribati",
"nationality": "I-Kiribati"
},
{
"iso2": "KM",
"countryName": "Comoros",
"nationality": "Comoran, Comorian"
},
{
"iso2": "KN",
"countryName": "Saint Kitts and Nevis",
"nationality": "Kittitian or Nevisian"
}];
let index = a.findIndex(e => e.iso2 === 'KN');
a[0] = (_=a[index], a[index] = a[0],_);
console.log(a)
Or can remove the element using Array.splice
and then unshift.
const a = [{
"iso2": "KH",
"countryName": "Cambodia",
"nationality": "Cambodian"
},
{
"iso2": "KI",
"countryName": "Kiribati",
"nationality": "I-Kiribati"
},
{
"iso2": "KN",
"countryName": "Saint Kitts and Nevis",
"nationality": "Kittitian or Nevisian"
},
{
"iso2": "KM",
"countryName": "Comoros",
"nationality": "Comoran, Comorian"
}];
let index = a.findIndex(e => e.iso2 === 'KN');
e = a.splice(index,1);
a.unshift(...e)
console.log(a)
๐คAZ_
0๐
You can use Array.sort
to re-order the array as you wish.
const a = [{
"iso2": "KH",
"countryName": "Cambodia",
"nationality": "Cambodian"
},
{
"iso2": "KI",
"countryName": "Kiribati",
"nationality": "I-Kiribati"
},
{
"iso2": "KM",
"countryName": "Comoros",
"nationality": "Comoran, Comorian"
},
{
"iso2": "KN",
"countryName": "Saint Kitts and Nevis",
"nationality": "Kittitian or Nevisian"
}
];
a.sort((item1) => item1.iso2 === 'KN' ? -1 : 1);
console.log(a);
๐คfelixmosh
0๐
try this:
let data = [
{
iso2: "KH",
countryName: "Cambodia",
nationality: "Cambodian"
},
{
iso2: "KI",
countryName: "Kiribati",
nationality: "I-Kiribati"
},
{
iso2: "KM",
countryName: "Comoros",
nationality: "Comoran, Comorian"
},
{
iso2: "KN",
countryName: "Saint Kitts and Nevis",
nationality: "Kittitian or Nevisian"
}
];
let one = "KN";
data.sort((x, y) => (x.iso2 == one ? -1 : y.iso2 == one ? 1 : 0));
console.log(data);
๐คEvan
0๐
You can simply reverse your array if you want to last object on top.
a.reverse();
๐คAnuj Gupta
Source:stackexchange.com