user9529942
user9529942

Reputation:

Get percentage value from difference between two arrays javascript

I have 2 arrays :

var a = [120, 148, 50]
var b = [90, 100, 150] 

How I can get the difference pourcentage between a and b like :

var c = [ -28.57, -38.71 , 100 ]

i.e: the difference between 120 and 90 equal -28.57

Thank's for your help

Upvotes: 1

Views: 1852

Answers (4)

Mr. Polywhirl
Mr. Polywhirl

Reputation: 48630

You want to calculate the percentage increase.

% Increase = [(new value - orig value) / orig value] * 100

const increasePercentage = (n, m) => (m - n) / n * 100

let a = [120, 148, 50]
let b = [90, 100, 150] 
let c = a.map((n, i) => increasePercentage(n, b[i]))

console.log(c); // [ -25%, -32.43%, 200% ]


If you want to calculate the percentage difference that PEPEGA mentioned, just alter the formula.

% Difference = [(new value - orig value) / ((new value + orig value) / 2)] * 100

const increaseValue = (n, m) => (m - n) / ((m + n) / 2) * 100

let a = [120, 148, 50]
let b = [90, 100, 150] 
let c = a.map((n, i) => increaseValue(n, b[i]))

console.log(c); // [ -28.57%, -38.71%, 100% ]

Upvotes: 2

PEPEGA
PEPEGA

Reputation: 2283

You can use 100 * ((B-A) / ((B+A)/2)) to find the percentage diff of two values

var a = [120, 148, 50]
var b = [90, 100, 150] 

var res = a.map((x, i) => 100 * ((b[i] - x) / ((b[i] + x)/2 )))

console.log(res);

Upvotes: 1

baao
baao

Reputation: 73241

You can simply loop and calculate the difference there

const a = [120, 148, 50];
const b = [90, 100, 150];

const diffPercent = [];

for (let i = 0; i<a.length; i++) {
    diffPercent.push(((b[i] - a[i]) / ((b[i] + a[i]) / 2)) * 100)
}

console.log(diffPercent);

Upvotes: 1

Janak Prajapati
Janak Prajapati

Reputation: 886

Hope this helps

I have created function to identify percentage difference, it can be either positive or negative

To get absolute value i have added Math.abs so diff will be always in positive integer

<script type="text/javascript">
function perDifference(a, b) {
    let percent;
    if(b !== 0) {
        if(a !== 0) {
            percent = (b - a) / a * 100;
        } else {
            percent = b * 100;
        }
    } else {
        percent = - a * 100;            
    }       
    return (percent);
    }
var a = [120, 148, 50]
var b = [90, 100, 150] 
var c = [];
for(i=0; i<a.length; i++) {
    c.push(Math.abs(perDifference(a[i],b[i])));

}
console.log(c)

    </script>

Upvotes: -1

Related Questions