skip to Main Content

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


  1. 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.

    var array = [{
        "identifier": "A",
      },
      {
        "identifier": "B",
      },
      {
        "identifier": "C",
      },
      {
        "identifier": "D",
      },
    ]
    const bIndex = array.findIndex(arr => (arr.identifier == "B"));
    const removed = array.splice(bIndex,1);
    array.push(...removed);
    console.log("resorted array",array)
    Login or Signup to reply.
  2. For mapping (i.e. creating a new array), you can concatenate the slices (before, after, itself):

    const array = [{identifier:"A"},{identifier:"C"},{identifier:"D"},{identifier:"B"}];
    
    const i = array.findIndex(o => o.identifier === 'X');
    const result = i < 0 ? [...array]
                         : [...array.slice(0, i), ...array.slice(i+1), array[i]];
    console.log(result);

    If you are really looking for a solution that uses the map method, then use the index parameter that the map-callback gets:

    const array = [{identifier:"A"},{identifier:"C"},{identifier:"D"},{identifier:"B"}];
    
    let move = null;
    const result = array.map((o, i, array) => {
        if (o.identifier === 'B') move = o;
        return array[i + !!move] ?? move;
    });
    console.log(result);
    Login or Signup to reply.
  3. 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)

    Login or Signup to reply.
  4. You could take a generator and delay the wanted item.

    function* moveToEnd(array, identifier) {
        let last = [];
        
        for (const element of array)
            if (element.identifier === identifier) last.push(element);
            else yield element;
            
        yield* last;
    }
    
    const
        array = [{ identifier: "A" }, { identifier: "B" }, { identifier: "C" }, { identifier: "D" }],
        result = [...moveToEnd(array, 'B')];
    
    console.log(result);
    Login or Signup to reply.
  5. 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 to id to make the code more readable.

    const arr = [{"id": "A"},{"id": "B"},{"id": "C"},{"id": "D"}];
    
    const sortedArr = arr.sort(
      (a, b) => a.id === 'B' 
                  ? 1 
                  : b.id === 'B' 
                    ? -1 
                    : 0
    );
    
    console.log(sortedArr);
    Login or Signup to reply.
  6. As @jonrsharpe pointed out, you can apply sort():

    const array = [
      {
        identifier: 'A',
      },
      {
        identifier: 'B',
      },
      {
        identifier: 'C',
      },
      {
        identifier: 'D',
      },
    ];
    array.sort((a, b) => (b.identifier === 'B' ? -1 : 0));
    console.log(array);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search