3

I'm trying to create a pure function that receives an array as parameter and now I want to replace an element at a given index without modifying the provided array argument.

Basically I'm looking for something like this:

export const muFunc = (arr) => {
    return arr.replaceElementAt(1, 'myNewValue'); // This doesnt modify arr at all
}

How can I do that?

6
  • 1
    Can you not copy the array and splice? Commented Aug 16, 2016 at 13:09
  • As the topic says - I'm trying to find out if it's possible without creating a copy of the array Commented Aug 16, 2016 at 13:09
  • arr.slice() will give you an array clone Commented Aug 16, 2016 at 13:10
  • @user2394156 I don't think so. JavaScript doesn't have Ruby's modifier! distinction. Commented Aug 16, 2016 at 13:11
  • Why do you need to do this? Why is copying the array not sufficient? Commented Aug 16, 2016 at 13:28

4 Answers 4

6

Simply copy the array. A simple way to do that is slice:

export const muFunc = (arr) => {
    var newArray = arr.slice();
    newArray[1] = 'myNewValue';
    return newArray;
};

From a comment on the question:

As the topic says - I'm trying to find out if it's possible without creating a copy of the array

No it's not possible — well, not reasonably. You have to either modify the original, or make a copy.

You could create proxy object that just returns a different value for the "1" property, but that seems unnecessarily complicated.

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

Comments

2

You could take advantage of Object.assign and do something like:

const arr = [1, 2, 3, 4, 5];
const updatedArr = Object.assign([], arr, {1: 'myNewValue'});

console.log(arr); // [1, 2, 3, 4, 5]
console.log(updatedArr); // [1, "myNewValue", 3, 4, 5]

Comments

-1

You can use map function to achieve this

var arr = [1,2,3,4,5,6,7,89];

arr.map(function (rm) {
    if (rm == 2) {
        return 3
    } else {
        return rm
    }
})

Comments

-1

Try this :

function replace(l) {
    return l.splice("new value",1);
};
var x = replace(arr);

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.