Home > Enterprise >  How to compare two arrays and then return the sum of all elements of the array before the changed el
How to compare two arrays and then return the sum of all elements of the array before the changed el

Time:06-17

I have two arrays that I need to check the difference upon and return the sum of all elements of the array before the changed element and includes him.

I currently have two arrays of area height that get updated when the input's value is changed. Also can be changed 2 or more elements of array, then need sum all changed elements and all elements before last changed element.

For example arrays:

let oldArea = [3, 4, 2]

let newArea = [3, 6, 2]

I tried something like this (it does its job partially, but the array length can be 5 or more elements, so this solution is bad) :

let oldArea = [3, 4, 2]
let newArea = [3, 6, 2]

let changedArea = [];

if (
  oldArea[0] !== newArea[0] &&
  oldArea[1] === newArea[1]
) {
  changedArea.push(newArea[0]);
} else if (
  oldArea[1] !== newArea[1] &&
  oldArea[0] === newArea[0] &&
  oldArea[2] === newArea[2]
) {
  changedArea.push(newArea[0]   newArea[1]);
} else changedArea.push(newArea.reduce((a, b) => a   b, 0));

let changedAreaHeight = changedArea.reduce((a, b) => a   b, 0);

console.log(changedAreaHeight)

Example

I will be grateful for any tips with other solutions.

CodePudding user response:

You can use a simple for loop and break when the elements are not same

let oldArea = [3, 4, 2]
let newArea = [3, 6, 2]

let final = 0;

for (let i = 0; i < newArea.length; i  ) {
  if (newArea[i] === oldArea[i]) {
    final  = newArea[i]
  } else {
    final  = newArea[i]
    break;
  }
}

console.log(final)

  • Related