Reputation: 3527
I have an array of arrays, each one of them consists of two values - timestamp and price.
[
[1147651200000, 376.2],
[1147737600000, 350],
[1147824000000, 374.5]
]
I need to find date and time in which price was the lowest among all points. What function should I use, pls help.
EDIT:
Thanks everyone! I took tests to to see which function is fastest. Here is how I did it (example with .sort, others are same)
console.time('cycle');
var k = 0;
while (k<10000) {
var input = [
[1147651200000, 376.2],
[1147737600000, 350],
[1147824000000, 374.5]
];
var output = input.sort(function(a,b){
return a[1] > b[1];
})[0];
k++;
}
console.log(output);
console.timeEnd('cycle'); //36 ms
.map //67 ms
minimum in cycle // 108 ms
Upvotes: 1
Views: 1579
Reputation: 782
Maybe something like this?
var min = arr[0][1];
var timestamp = 0;
for(i in arr) {
if(arr[i][1] <= min ) {
min = arr[i][1];
timestamp = arr[i][0];
}
}
Upvotes: 0
Reputation: 281375
Sorting the array is O(N logN) - if performance with large arrays might be an issue, here's an O(N) solution:
var min = a[0];
for (var i = 1; i < a.length; i++) {
if (a[i][1] < min[1]) {
min = a[i];
}
}
// min is now [1147737600000, 350]
Upvotes: 2
Reputation: 318182
Get the numbers from the array into a new array, use Math.min to get the lowest, and backtrack to get the timestamp.
var arr = [
[1147651200000, 376.2],
[1147737600000, 350],
[1147824000000, 374.5]
]
var numbs = arr.map(function(x) { return x[1]||0 });
var timestamp = arr[numbs.indexOf(Math.min.apply( Math, numbs ))][0];
Upvotes: 1
Reputation: 152206
Just try with:
var input = [
[1147651200000, 376.2],
[1147737600000, 350],
[1147824000000, 374.5]
];
var output = input.sort(function(a,b){
return a[1] > b[1];
})[0];
Output:
[1147737600000, 350]
Upvotes: 5