0

For example, I know I can use spread operator to add an element to an array in ES6.

const arr = ["a","b"]
const newArr = [...arr, "c"]

that I get

["a","b","c"]

But how to implement this in an nested array, like

const arr = [["a","b"], ["d"]]

I want to get

newArr1 = [["a","b","c"], ["d"]]

and

newArr2 = [["a","b"],["d","c"]]

Perhaps we can use

[[...arr[0], 'c'], [...arr[1]]]

but what if

const arr = [["a","b"], ["d"],["e"]]

and I still want

[["a","b","c"], ["d"],["e"]]
is there a common way?
3
  • Maybe mapping the spread operator to each element? Commented Aug 22, 2022 at 4:28
  • Is that what you meant? [[...arr[0], 'c'], [...arr[1]]] Commented Aug 22, 2022 at 5:26
  • yeah Alexandr you're right! But what if the size is not fixed? Like const arr = [["a","b"], ["d"],["e"]] Commented Aug 22, 2022 at 14:05

1 Answer 1

1

You can simply use the array index or use findIndex and find methods, in case you want to remove not based on the index

const arr = [[a,b], [d]]
arr[1].push(c)
//arr = [[a,b], [c,d]]
const arr = [['a', 'b'], ['d']]
const array = [...arr]
const arrayIndex = array.findIndex(item => item.find(i => i === 'd'))
if (arrayIndex !== -1) {
  const oldArray = array.find(item => item.find(i => i === 'd'))
  const newArray = [...oldArray, 'c']
  array[arrayIndex] = newArray
}
console.log(array);
Sign up to request clarification or add additional context in comments.

2 Comments

Yes, but what if I don't want to mutate the original array
You can create a new variable that recieves your original array value and spread it. I just edit the post.

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.