Home > Net >  How can I combine 2 arrays key and value in JavaScript?
How can I combine 2 arrays key and value in JavaScript?

Time:09-02

I'm building my first project, an expense tracking app with React Native. It's going very well.

I would like to concat the following 2 arrays.

[{"Day": "08/31/2022"}, {"Day": "09/01/2022"}, {"Day": "08/31/2022"}, {"Day": "08/31/2022"}, {"Day": "08/31/2022"}, {"Day": "08/31/2022"}]

[{"Amount": "40"}, {"Amount": "300"}, {"Amount": "1715"}, {"Amount": "250"}, {"Amount": "100"}, {"Amount": "200"}]

Final results should be:

[{"Day": "08/31/2022", "Amount": "40"}, {"Day": "09/01/2022","Amount": "300"}, {"Day": "08/31/2022","Amount": "1715"}, {"Day": "08/31/2022","Amount": "250"}, {"Day": "08/31/2022","Amount": "100"}, {"Day": "08/31/2022","Amount": "200"}]

My current code:

  const q = query(collection(db, "users"), where("moneda", "==", "$"));
  const unsubscribe = onSnapshot(q, (querySnapshot) => {
    const dolarCurrency = [];
    const months =[];
    querySnapshot.forEach((doc) => {
        dolarCurrency.push(doc.data().cantidad);
        months.push(doc.data().fecha)
    });

    const hash = months.map((Day) => ({ Day }));
    const hashDolar = dolarCurrency.map(( Amount ) => ({ Amount }))
  });

Everything is working fine, and I'm pulling live data from my firebase to convert it into a chart on React Native with Victory Native for all my personal expenses. So, this would be my last step.

Any help or advice is appreciated!

CodePudding user response:

You can use Array#map and object destructuring as follows:

const days = [{"Day": "08/31/2022"}, {"Day": "09/01/2022"}, {"Day": "08/31/2022"}, {"Day": "08/31/2022"}, {"Day": "08/31/2022"}, {"Day": "08/31/2022"}],

      amounts = [{"Amount": "40"}, {"Amount": "300"}, {"Amount": "1715"}, {"Amount": "250"}, {"Amount": "100"}, {"Amount": "200"}],
      
      output = days.map(({Day},i) => ({Day, ...amounts[i]}));
      
      console.log( output );

CodePudding user response:

Here's a workaround if you want to apply some validations or use fallback value in cases such as if one array has more items than the other one:

function combine(array1, array2) {
  // If either one is not an array or if both are empty, return an empty array.
  if (
    !Array.isArray(array1) ||
    !Array.isArray(array2) ||
    (!array1.length && !array2.length)
  ) {
    return [];
  }
  
  // If one array is empty, return the other one.
  if (array1.length && !array2.length) {
    return array1;
  }
  
  if (!array1.length && array2.length) {
    return array2;
  }

  let arrayToLoop = array1;
  let otherArray = array2;
  
  // If array2 has more items than array1, loop array2 instead.
  if (array2.length > array1.length) {
    arrayToLoop = array2;
    otherArray = array1;
  }
  
  return arrayToLoop.map((item, index) => {
    // Return the current item if it has no match.
    if (!otherArray[index]) {
      return item;
    }
    
    // Else, merge with otherArray's current item.
    return {
      ...item,
      ...otherArray[index],
    };
  })
}

console.log(combine(arr1, arr2))
  • Related