valdimar.ein
valdimar.ein

Reputation: 35

JavaScript: Working with Two Arrays of Objects

//Before
export const arr1 = [
    { addKey: '11', address: '12', value: 0 },
    { addKey: '11', address: '12', value: 0 },
    { addKey: '12', address: '11', value: 0 },
    { addKey: '12', address: '11', value: 0 },
]

export const arr2 = [
    {address: '11', value: 5, total: 0 },
    {address: '12', value: 10, total: 0 },
]

I want to create a function with arr1 & arr2 as arguments.

Where arr1.address == arr2.address => take arr2.value => Put in arr1.value

Sum the values by addKey then add to arr2.total

//After
export const arr1After = [
    { addKey: '11', address: '12', value: 10 },
    { addKey: '11', address: '12', value: 10 },
    { addKey: '12', address: '11', value: 5 },
    { addKey: '12', address: '11', value: 5 },
]

export const arr2After = [
    {address: '11', value: 5, total: 20 },
    {address: '12', value: 10, total: 10 },
]

Upvotes: 1

Views: 48

Answers (1)

Drashti Kheni
Drashti Kheni

Reputation: 1140

Try this once:

//using for loop
const changeValue = (arr1, arr2) => {
   for (let i = 0; i < arr1.length; i++) {
    for (let j = 0; j < arr2.length; j++) {
      if (arr1[i].address === arr2[j].address) {
        arr1[i].value = arr2[j].value;
        arr2[j].total += arr2[j].value;
      }
    }
  }
  console.log(arr1, arr2);
};

//using foreach loop
const changeValue = (arr1, arr2) => {
   arr1.forEach((arr1Elem) => {
    arr2.forEach((arr2Elem) => {
      if (arr1Elem.address === arr2Elem.address) {
        arr1Elem.value = arr2Elem.value;
        arr2Elem.total += arr2Elem.value;
      }
    });
  });

  console.log(arr1, arr2);
};

changeValue(arr1, arr2);

Upvotes: 1

Related Questions