Reputation: 29
I need find the minimum value from a two-dimensional array. But something goes wrong, someone can explain me please?
let array = [
[20, 34, 2],
[9, 12, 18],
[3, 4, 5]
];
let str = array.join(",");
console.log(str);
let array_2 = str.split(",");
console.log(array_2);
let minValue = array_2[0];
for (let i = 0; i < array_2.length; i++) {
if (array_2[i] < minValue) {
minValue = array_2[i];
}
}
console.log(minValue);
Upvotes: 1
Views: 67
Reputation: 5004
Convert your Strings to Number before the comparison
let array = [
[20, 34, 2],
[9, 12, 18],
[3, 4, 5]
];
let str = array.join(",");
console.log(str);
//here you convert to number
let array_2 = str.split(",").map(Number);
console.log(array_2);
Initialize minValue with the highest possible value
you should use Number.MAX_VALUE;
let minValue = Number.MAX_VALUE;
All together
let array = [
[20, 34, 2],
[9, 12, 18],
[3, 4, 5]
];
let str = array.join(",");
console.log(str);
let array_2 = str.split(",").map(Number);
console.log(array_2);
let minValue = Number.MAX_VALUE;
for (let i = 0; i < array_2.length; i++) {
if (array_2[i] < minValue) {
minValue = array_2[i];
}
}
console.log(minValue);
Upvotes: 0
Reputation: 386530
The canonical way is to flatten the array with Array#flat
and get the minimum with Math.min
by spreading the values (spread syntax ...
).
let array = [[20, 34, 2], [9, 12, 18], [3, 4, 5]];
console.log(Math.min(...array.flat()));
Upvotes: 2
Reputation: 89139
You need to convert the strings to numbers so that numerical comparison is used instead of lexicographical comparison.
let array = [
[20, 34, 2],
[9, 12, 18],
[3, 4, 5]
];
let str = array.join(",");
console.log(str);
let array_2 = str.split(",").map(Number);//convert to number
console.log(array_2);
let minValue = array_2[0];
for (let i = 0; i < array_2.length; i++) {
if (array_2[i] < minValue) {
minValue = array_2[i];
}
}
console.log(minValue);
Alternatively, you could use Array#flat
on the original array so that you do not need to join
and split
.
let array = [
[20, 34, 2],
[9, 12, 18],
[3, 4, 5]
];
let array_2 = array.flat();
console.log(array_2);
let minValue = array_2[0];
for (let i = 0; i < array_2.length; i++) {
if (array_2[i] < minValue) {
minValue = array_2[i];
}
}
console.log(minValue);
Upvotes: 2