-2

Hey I have the following array :

var ar = [{id: "F"}, {id: "G"}, {id: "Z"}, {id: "ZZ"}]

I would like to move the one with the id equals to ZZ to the first position in the array. I know how to do it using several different functions, but I was wondering if there was an elegant solution to do it (lodash, ...)

Scipion
  • 11,449
  • 19
  • 74
  • 139

2 Answers2

2

You could use unshift() to add to start of array and splice() and findIndex() to get object by id.

var arr = [{id: "F"}, {id: "G"}, {id: "Z"}, {id: "ZZ"}]
arr.unshift(arr.splice(arr.findIndex(e => e.id == "ZZ"), 1)[0])

console.log(arr)
Nenad Vracar
  • 118,580
  • 15
  • 151
  • 176
1

var ar = [{
  id: "F"
}, {
  id: "G"
}, {
  id: "Z"
}, {
  id: "ZZ"
}];
ar.sort(function(a, b) {
  if (a.id === "ZZ") {
    return -1;
  }
  if (b.id === "ZZ") {
    return 1;
  }
  return 0;
});
console.log(ar);

How about sorting it?

blackmiaool
  • 5,234
  • 2
  • 22
  • 39