Let’s say I have this array of objects:
var array = [
{
"identifier": "A",
},
{
"identifier": "B",
},
{
"identifier": "C",
},
{
"identifier": "D",
},
]
How can I map/reduce this array to get this result:
var array = [
{
"identifier": "A",
},
{
"identifier": "C",
},
{
"identifier": "D",
},
{
"identifier": "B",
},
]
In other words, how can I put "B" at the end of array no matter how large the array is?
array.map((o) => {
if (o.identifier === 'B') {
// do what here?
}
return o;
})
6
Answers
Start by finding the index where identifier == "B", then splice the array at that index (this returns an array of the deleted item(s), then push the removed item(s) to the end of the original array.
For mapping (i.e. creating a new array), you can concatenate the slices (before, after, itself):
If you are really looking for a solution that uses the
map
method, then use the index parameter that the map-callback gets:var given_array = [ { "identifier": "A" }, { "identifier": "B" }, { "identifier": "C" }, { "identifier": "D" } ]; const index = array.findIndex(o => o.identifier === ‘B’); if(!index ==-1){ const item.splice(index, 1); given_array.push(item); console.log(given_array)
You could take a generator and delay the wanted item.
You can achieve the desired result in one simple
Array.prototype.sort()
call, with a very simple sort predicate.In the example I’ve shortened
identifier
toid
to make the code more readable.As @jonrsharpe pointed out, you can apply sort():