Home > Enterprise >  How to combine two arrays into a single? (React JS)
How to combine two arrays into a single? (React JS)

Time:05-09

There are two arrays like the one below.

const arrayA = {
 0: {
  id: XXXXXXX,
  name: "test"
 },
 1: {
  id: YYYYYYY,
  name: "example"
 }
}


const arrayB = {
  0: {
    id: XXXXXXX,
    category: "sea",
  }
  1: {
    id: YYYYYYY,
    category: "mountain"
  }
}

I would like to combine these two arrays into a single one by each id like the below:

array C = {
 0: {
  id: XXXXXXX,
  name: "test",
  category: "sea",
 },
 1: {
  id: YYYYYYY,
  name: "example",
  category: "mountain"
 }  
}

What is the smartest way to do this?

CodePudding user response:

Actually, there are not arrays but objects having keys like indexes. You can use Object.keys for the iteration and merge them by keys through objects.

const arrayA = {
 "0": {
  id: 0,
  name: "test"
 },
 "1": {
  id: 1,
  name: "example"
 }
}


const arrayB = {
  "0": {
    id: 0,
    category: "sea",
  },
  "1": {
    id: 1,
    category: "mountain"
  }
}

const arrayC = {}

for(const key of Object.keys(arrayA)) {
   arrayC[key] = {
      ...arrayA[key],
      ...arrayB[key],
   }
}

console.log(arrayC)

You also can use reduce instead of an usual iteration

const arrayA = {
  "0": {
    id: 0,
    name: "test"
  },
  "1": {
    id: 1,
    name: "example"
  }
}


const arrayB = {
  "0": {
    id: 0,
    category: "sea",
  },
  "1": {
    id: 1,
    category: "mountain"
  }
}

const arrayC = Object.keys(arrayA).reduce((result, key) => ({
  ...result,
  [key]: {
    ...arrayA[key],
    ...arrayB[key]
  }
}), {})

console.log(arrayC)

  • Related