1
//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 },
]

2
  • are the values of address distinct in arr2After? Commented Oct 18, 2022 at 9:50
  • As in they're all unique? If so yes. Commented Oct 18, 2022 at 9:53

1 Answer 1

1

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);
Sign up to request clarification or add additional context in comments.

2 Comments

This is missing the calculation of total ...
Thank you! That is super helpful! I had spent quite some time playing with this.

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.