Home > Mobile >  JavaScript - change index position of multiple objects in array
JavaScript - change index position of multiple objects in array

Time:12-01

How would move one or more objects in an array up 1 position in the index, assuming I have a separate array of the ids to be moved (vanilla or Lodash).

Presumably I'd use splice() but I'm not sure how to use it in this more complicated context.

E.g.:

// use this array of rowids

const rowsToBeMoved = ['row4', 'row5']; 

// target the objects bearing those row ids in an array of objects:

const rowsArr = [
  { rowid: "row0", name: "Mark Johnson" },
  { rowid: "row1", name: "Jill Trillian" },
  { rowid: "row2", name: "Alan Drangson" },
  { rowid: "row3", name: "Bill Greggory" },
  { rowid: "row4", name: "Alice Walker" },
  { rowid: "row5", name: "Kurt Rose" },
];

// move both objects up 1 position in the index so the result is this:

const orderedRowsArr = [
  { rowid: "row0", name: "Mark Johnson" },
  { rowid: "row1", name: "Jill Trillian" },
  { rowid: "row2", name: "Alan Drangson" },
  { rowid: "row4", name: "Alice Walker" },
  { rowid: "row5", name: "Kurt Rose" },
  { rowid: "row3", name: "Bill Greggory" },
];

This is what I have so far. I'm able to get the indexes of the rows to be moved, but I don't know how to apply splice() to it.

let moveIndexes = [];
this.rowsArr.forEach((row) => {
  moveIndexes.push(
    this.collection.rows.findIndex((r) => r.rowid === row.rowid)
  );
});

CodePudding user response:

const rows = [
  { rowid: "row0", name: "Mark Johnson" },
  { rowid: "row1", name: "Jill Trillian" },
  { rowid: "row2", name: "Alan Drangson" },
  { rowid: "row3", name: "Bill Greggory" },
  { rowid: "row4", name: "Alice Walker" },
  { rowid: "row5", name: "Kurt Rose" },
]
const rowsToBeMoved = ['row4', 'row5']

let c = 0
let a = rowsToBeMoved.map(id=>rows.findIndex(i=>i.rowid===id)).sort()
console.log(rows.map((_,i)=>a.includes(i 1)?(c  , rows[i 1]):rows[i-c]))

  • Related