user6924814 user6924814 - 1 month ago 6
PHP Question

how to compare values of two array in javascript

I have two array with minimum and maximum value. I want to make foreach loop where if minimum and maximum values matches then only display maximum value and if both the values don't match then display both the values min and max respectively. I want to match the key of min and max values. I am not getting how do i compare two values. I have this array

var interestRateMin = [];
data.forEach(function(element){
this.push(element.interestRateMin);
}, interestRateMin );

var interestRateMax = [];
data.forEach(function(element){
this.push(element.interestRateMax);
}, interestRateMax );


This is the array value which i get.

MinRate = ["10.0", "11.5", "12.0", "12.0", "12.0", "12.0", "12.0", "12.25", "12.5", "12.75", "12.75", "13.0", "13.0", "13.25", "13.5", "13.75", "14.0", "14.0"]

MaxRate = ["10.0", "11.75", "12.0", "12.0", "24.0", "12.0", "12.0", "12.25", "12.5", "12.75", "12.75", "13.0", "13.0", "13.25", "17.0", "13.75", "14.0", "14.0"]


I want to achieve same thing but in javascript.

<?php
foreach ($json['resultList'] as $key=>$value) {
if($json["resultList"][$key]["MinRate"] == $json["resultList"][$key]["MaxRate"]){
$interest = $json["resultList"][$key]["MinRate"];
}
else{
$interest = $json["resultList"][$key]["MinRate"].' - '.$json["resultList"][$key]["MaxRate"];

}

if($json["resultList"][$key]["MinPercentage"] == $json["resultList"][$key]["MaxPercentage"]){
$financing = $json["resultList"][$key]["MinPercentage"];
}
else{
$financing = $json["resultList"][$key]["MinPercentage"].' - '.$json["resultList"][$key]["MaxPercentage"];

}
}


?>

Answer

You could iterate the arrays, make a comparison and return the combined result in a new array.

var minRate =  ["10.0", "11.5", "12.0", "12.0", "12.0", "12.0", "12.0", "12.25", "12.5", "12.75", "12.75", "13.0", "13.0", "13.25", "13.5", "13.75", "14.0", "14.0"],
    maxRate = ["10.0", "11.75", "12.0", "12.0", "24.0", "12.0", "12.0", "12.25", "12.5", "12.75", "12.75", "13.0", "13.0", "13.25", "17.0", "13.75", "14.0", "14.0"],
    result = minRate.map(function (a, i) {
        return a === maxRate[i] ? a : a + ' - ' + maxRate[i];
    });

console.log(result)

Comments