I have an array which holds a list of array and the value is in ‘dollars’.
I need to take the max price and min price from that list.
This is what have tried,
var _array = [$1.09,$3.07,$2.223];
var number = Number(_array.replace(/[^0-9.]+/g,""));
a= Math.max.apply(Math,number); // $3
b= Math.min.apply(Math,number); // $1
But its not working, can anyone please help me out.
It could be simple if you correct the error in your list array sort is your friend
var _array = ["$1.09", "$3.07", "$2.223"];
_array.sort(function(a, b) {
return Number(a.replace(/[^0-9.]+/g, "")) - Number(b.replace(/[^0-9.]+/g, ""));
});
console.log(_array[0], " ", _array[_array.length - 1]);
Open your browser inspector and run the above code.
Thanks to @Meze for his contribution that makes 10.01 higher than 2 or the likes
Problem is you are having illegal characters in your array. Have them like strings by wrapping in ''
.
Do it like bellow
var _array = ['$1.09','$3.07','$2.223'];
var numbers = _array.map(function(curr){
return Number(curr.replace(/[^0-9.]+/g,""))
})
a= Math.max.apply(Math,numbers); // 3
b= Math.min.apply(Math,numbers); // 1
console.log(a,b)
NOTE:- The .map
function won’t work on IE8 so you can use for
loop there. Like bellow
var _array = ['$1.09','$3.07','$2.223'];
var numbers = [];
for(var i=0;i<_array.length;i++){
numbers.push(_array[i].replace(/[^0-9.]+/g,""));
}
a= Math.max.apply(Math,numbers); // 3
b= Math.min.apply(Math,numbers); // 1
console.log(a,b)