简体   繁体   中英

How to add an element to an array inside an array in JS ES6?

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?

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 array = [['a', 'b'], ['d']]
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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM