2

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)
  );
});
5
  • Is the data in rowsToBeMoved must be next to each other? Commented Dec 1, 2022 at 1:53
  • 1
    rowsToBeMoved = ['row4', 'row5'] but row3 and row4 are moved in the result instead, why? Commented Dec 1, 2022 at 2:50
  • what if rowsToBeMoved = ['row0']? Commented Dec 1, 2022 at 2:57
  • If I've read your question correctly, then if Alice and Kurt are both moved up one position, then Bill should be last. Either I've not understood your question, or your question is worded incorrectly, or your test case is wrong Commented Dec 1, 2022 at 3:22
  • @Layhout my mistake. Fixed OP. Commented Dec 1, 2022 at 6:24

1 Answer 1

1

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]))

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.