0

How do I immutably insert an element into a sorted array? (Let's assume an array of integers for simplicity)

The reason for this question: I'm writing a reducer for a React app, where the order of elements in my particular array is important.

The closest solution I've found is this one here, but it doesn't cover insertions into a sorted array.

Cog
  • 1,545
  • 2
  • 15
  • 27
  • 2
    What do you mean by "immutably insert"? Inserting is a mutation. Sounds like you just need to make a copy of the array, insert into the copy, and return that. – Barmar Sep 11 '19 at 23:13

1 Answers1

1

Try this one.

let sortedArr = [1,2,5,9,12];

const newItem = 7;

for (let i = 0; i < sortedArr.length; i++) {
  if (newItem <= sortedArr[i]) {
    sortedArr = [...sortedArr.slice(0, i), newItem, ...sortedArr.slice(i)];
    break;
  }
}
console.log(sortedArr);
Joven28
  • 769
  • 3
  • 12