0

I have an array that looks something like this:

uint256[] array = [1,2,3,4,5,6,7,8];

I am familiar with how to add an element to an array using array.push(100); which would make the array look like this:

[1,2,3,4,5,6,7,8,100];

How can I add an element to the array at an index of my choosing while altering the array size accordingly?

For instance, how do I add an element to the array at: index [3] or more specific array[3] = 999 while also increasing the size of the array accordingly?

The desired result would look something like this:

[1,2,3,999,4,5,6,7,8,100];
1

1 Answer 1

1

It looks like this has been answered here

I do see that this answer only applies to calldata, however. Here is my "top of brain" naive / brute force approach.

pseudo code:

function sliceNDice(string[] originalArr, uint replaceAtIndex, string insertMe) internal pure {
  tmpArr = [];
  for (let i=0; i < originalArr.length; i++) {
    if (i == replaceAtIndex) {
      tmpArr.push(insertMe);
      tmpArr.push(originalArr[i]);
    } else {
      tmpArr.push(originalArr[i]);
    }
  }
  return tmpArr;
}

// use like
sliceNDice(['foo', 'bar', 'baz'], 1, 'foobarbaz'); // ['foo', 'foobarbaz', 'bar', 'baz']

This is a super brute method and the code above certainly has syntax errors and can be improved (one push for example). I just wanted to give you an alternative way to think about this problem. Good luck!

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.