0

When type equals all, I need to combine two arrays into one. I have the code, but it gets the wrong result。

const arr = [{value: 'aa'}, {value: 'bb'}];
const arr2 = [{type: 'all'}, {type: 'text', value: 'a2'}, {type: 'all'}]
arr.forEach((item, index) => {
  arr2.forEach((items, indexs) => {
    if (items.type === 'all') {
      items.value = arr[index].value
    }
  })
})
console.log(arr2)

I hope to get this result

arr2 = [{type: 'all', value: 'aa'}, {type: 'text', value: 'a2'}, {type: 'all', value: 'bb'}]
console.log(arr2)

1 Answer 1

1

It's not a good idea to mutate the data that you're looping over.

If I understand correctly, you need to iterate through arr2 and intersperse items from arr when type is all.

I'd use Array.map for this sort of thing:

const arr = [{value: 'aa'}, {value: 'bb'}];
const arr2 = [{type: 'all'}, {type: 'text', value: 'a2'}, {type: 'all'}]

const combined = arr2.map(({type, ...rest})=>type==='all'?{type, ...arr.shift()}:{type, ...rest})

console.log(combined)

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

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.