1
let nestedArr = [[0,0],[0,0]]
let insideArr = nestedArr[0]
let targetArr = [1,1]

Basically I want to change the insideArr's elements to equal to targetArr, and it should change the first element of nestedArr too (because insideArr is refering to that).

insideArr = targetArr
insideArr = [..targetArr]

Above 2 approaches won't work because it will make insideArr pointing to new reference. I know using forEach to loop through insideArr and assign it one by one should work, but is there a better way? And BTW, should I avoid this kind of usage?

5
  • 1
    avoid this kind of usage for what? Commented May 25, 2021 at 1:38
  • 1
    Why not nestedArr[0] = targetArr? Why do you need to maintain insideArr as a reference to nestedArr[0]? Commented May 25, 2021 at 1:39
  • 1
    Got to say the close votes are ridiculously over-zealous. It's a perfectly valid question. Commented May 25, 2021 at 1:46
  • @ksav That's what I'm asking, I don't if this kind of editing will make the code less robust. Commented May 25, 2021 at 22:57

2 Answers 2

3

If you must maintain insideArr as a reference to nestedArr[0], you can use Array.prototype.splice() to mutate insideArr

let nestedArr = [[0,0],[0,0]]
let insideArr = nestedArr[0]
let targetArr = [1,1]

// Replace all of insideArr with targetArr
insideArr.splice(0, insideArr.length, ...targetArr)

console.log("still the same reference?", insideArr === nestedArr[0])
console.log("insideArr:", insideArr)
console.log("nestedArr:", nestedArr)
.as-console-wrapper { max-height: 100% !important; }

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

Comments

2

Assuming you have good reasons for keeping the reference the same - and sometimes there are, you can do:

let nestedArr = [
  [0, 0],
  [0, 0]
];
let insideArr = nestedArr[0];
let targetArr = [1, 1];
insideArr.length = 0;
insideArr.unshift(...targetArr); // insideArr.push(...targetArr) works fine too
console.log(nestedArr);

5 Comments

I prefer Phil's one-line answer using splice, but keeping this here to show there's more than one way to skin a cat.
Love the old .length = 0 trick. You could also use push instead of unshift (just because it's a more commonly understood method)
@Phil Honestly my first guess would've been that unshift adds them in the wrong order
Good point re being less well known, and honestly I'm not sure why I chose it over push! Added comment to code.

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.