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);
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);
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()));
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);
Related
I have an array of strings that, after a lot of effort, I have managed to turn into several arrays with a loop. So right now, the loop is giving me something like:
[4,5,6,7,8]
[4,5,6,7,8],[1,2,3,4,5]
[4,5,6,7,8],[1,2,3,4,5],[22,33,44,55,66]
If I place the return lower in the code, I get:
[[4,5,6,7,8],[1,2,3,4,5],[22,33,44,55,66]]
What I need is the vertical sum of these arrays, so in this case it'd be:
[27,40,53,66,80]
So far, I'm usign '.push'. Also, console.log gives me this answer but return results in 'undefined'. Any help with these two things would be welcome!
----UPDATE----
As someone here suggested, I tried this but it doesn't work entirely:
array=[ [ 1, 2, 4 ], [ 4, 1, 5 ], [ 0, 5, 2 ] ];
let adding=0
const result=[]
for (let i = 0; i < array[0].length; ++i) {
for (let j = 0; j < array.length; ++j) {
adding += array[j][i];
}
result.push(adding);}
console.log(result)
```
The ouput is: [ 5, 13, 24 ] instead of [5,8,11]
1) You can easily achieve the result using map and reduce
const arr = [
[4, 5, 6, 7, 8],
[1, 2, 3, 4, 5],
[22, 33, 44, 55, 66],
];
const result = arr[0].map((_, i) => arr.reduce((acc, curr) => acc + curr[i], 0));
console.log(result)
2) Using simple for loops
const arr = [
[4, 5, 6, 7, 8],
[1, 2, 3, 4, 5],
[22, 33, 44, 55, 66],
];
const result = [];
for (let i = 0; i < arr[0].length; ++i) {
let sum = 0;
for (let j = 0; j < arr.length; ++j) {
sum += arr[j][i];
}
result.push(sum);
}
console.log(result);
This question already has answers here:
Create copy of multi-dimensional array, not reference - JavaScript
(4 answers)
Closed 1 year ago.
What's wrong with this code?
let matrix1 = [
[2, 7, 9, 2],
[8, 0, 7, 1],
[8, 8, 0, 8]
];
let arr = []; // or arr = [[]];
for (let i = 0; i < matrix1.length; i++) {
for (let j = 0; j < matrix1[i].length; j++) {
arr[i][j] = matrix1[i][j];
}
}
console.log(arr);
Error is:
Cannot set property '0' of undefined
This is when I try to assign the value of an element of matrix1 to the new array.
for loop works for the single dimensional array.
try this
let matrix1 = [
[2, 7, 9, 2],
[8, 0, 7, 1],
[8, 8, 0, 8]
];
let arr = []; // or arr = [[]];
for (let i = 0; i < matrix1.length; i++) {
for (let j = 0; j < matrix1[i].length; j++) {
if(!arr[i])
arr[i] = []
arr[i][j] = matrix1[i][j];
}
}
if you want copy a 2d array without for loop try this one:
let matrix1 = [
[2, 7, 9, 2],
[8, 0, 7, 1],
[8, 8, 0, 8]
];
let arr = JSON.parse(JSON.stringify(matrix1))
You need to create a new sub array in the outer loop so that arr[i] is an array and not undefined
let matrix1 = [
[2, 7, 9, 2],
[8, 0, 7, 1],
[8, 8, 0, 8]
];
let arr = [];
for (let i = 0; i < matrix1.length; i++) {
// push a new sub array to be populated in next loop
arr.push([]);
for (let j = 0; j < matrix1[i].length; j++) {
arr[i][j] = matrix1[i][j];
}
}
console.log(arr);
The problem is the line arr[i][j] = matrix1[i][j];, since arr[i][j] is undefined at this point.
The correct way of adding elements to an array is using the .push() function:
let matrix1 = [
[2, 7, 9, 2],
[8, 0, 7, 1],
[8, 8, 0, 8]
];
let arr = [];
for (let i = 0; i < matrix1.length; i++) {
arr.push([]);
for (let j = 0; j < matrix1[i].length; j++) {
arr[i].push(matrix1[i][j]);
}
}
console.log(arr);
Also note that using JSON might achieve the same task in a simpler way:
let matrix1 = [
[2, 7, 9, 2],
[8, 0, 7, 1],
[8, 8, 0, 8]
];
let arr = JSON.parse(JSON.stringify(matrix1))
console.log(arr)
I'm trying to create a function that retrieves the diagonal values from a 2-d array:
input = [
[1, 2, 3, 4],
[5, 1, 2, 3],
[9, 5, 1, 2]
]
output = [[9], [5, 5], [1, 1, 1], [2, 2, 2], [3, 3], [4]]
I'm having trouble figuring out how to manipulate the indices in a nested loop... This is what I'm currently working with:
const diagonalValues = arr => {
let output = new Array(2*input.length);
for (let i = 0; i < output.length; i++) {
output[i] = [];
if (i < input.length) {
for (j = input.length-1; j>i-input.length; --j) {
console.log(i, j)
}
}
}
}
How can I accomplish this?
You could use get number of rows which is just number of arrays and number of columns which is number of elements in each inner array (assuming all arrays have the same number of elements), and based on that calculate the diagonal matrix.
const input = [
[1, 2, 3, 4],
[5, 1, 2, 3],
[9, 5, 1, 2]
]
const rows = input.length;
const columns = input[0].length;
const total = columns + rows - 1;
const result = [];
for (let i = rows - 1; i >= 0; i--) {
const row = input[i];
for (let j = 0; j < columns; j++) {
const el = input[i][j];
const pos = j + rows - i - 1;
if (!result[pos]) {
result[pos] = []
}
result[pos].unshift(el)
}
}
console.log(JSON.stringify(result))
You can do the same with reduceRight and forEach methods.
let input = [
[1, 2, 3, 4, 4],
[5, 1, 2, 8, 3],
[9, 5, 1, 2, 2],
[9, 5, 1, 2, 1]
]
const result = input.reduceRight((r, a, i) => {
a.forEach((e, j) => {
const pos = j + (input.length - i - 1)
if(!r[pos]) r[pos] = []
r[pos].unshift(e)
})
return r;
}, []);
console.log(JSON.stringify(result))
You can use this algorithm to retrieve the diagonal values from 2d-input array.
const input = [
[1, 2, 3, 4],
[5, 1, 2, 3],
[9, 5, 1, 2]]
let output = []
input.forEach(res => {
res.forEach(resp => {
// if length of array is equel to 1
if (output.filter(x => x == resp).length > 0) {
output.filter(x => x == resp)[0].push(resp)
//if length of array is greater than 1
} else if (output.filter(x => x[0] == resp).length > 0) {
output.filter(x => x[0] == resp)[0].push(resp)
} else {
let temp = []
temp.push(resp)
output.push(temp)
}
})
})
output.forEach(o => console.log(JSON.stringify(o)));
let input = [
[1, 2, 3, 4],
[5, 1, 2, 8],
[9, 5, 1, 2],
[9, 5, 1, 2],
[9, 5, 1, 2],
];
let out = [];
for (let i = 1 - input.length; i < input[0].length; i++) {
let o = [];
let y = Math.max(-i, 0);
let x = Math.max(i, 0);
while (x < input[0].length && y < input.length)
o.push(input[y++][x++]);
out.push(o)
}
out.forEach(o => console.log(JSON.stringify(o)));
function largestOfFour(arr) {
var max = 0;
var newArr = [];
for (var i = 0; i < arr.length; i++) {
for (var j = i; j < arr.length; j++) {
max = Math.max(max, arr[i][j]);
}
newArr.push(max);
}
return newArr;
}
Here is my code. It works for me but I want to know is there any other sort way to do this?
Try this:
function largestOfFour(arr) {
return arr.map(function(item){
return Math.max.apply(null, item);
});
}
You may use the spread operator as:
var data = [
[1, 2, 3, 4],
[10, 20, 200, 31],
[21, 3, 444, 133],
[0, 0, 90, 1]
];
const max = Math.max(...data.map(inner => Math.max(...inner)));
console.log(max);
You can try something like this:
Idea, Math.max takes n arguments and gives you the max value. Using .apply you can pass parameters as array. Combining both will give you max value in an array.
Apply
var data = [
[1, 2, 3, 4],
[10, 20, 200, 31],
[21, 3, 444, 133],
[0, 0, 90, 1]
];
var max_arr = data.map(function(a) {
return Math.max.apply(this, a);
});
console.log(max_arr)
Sort + slice + pop
var data = [
[1, 2, 3, 4],
[10, 20, 200, 31],
[21, 3, 444, 133],
[0, 0, 90, 1]
];
var max_arr = data.map(function(a) {
return a.sort().slice(-1).pop()
});
console.log(max_arr)
I have a function that picks all elements from a 2-dimensional array by its rows and returns a 1-dimensional array.
The array has a variable amount of columns and rows.
Example:
let arr = [
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12]
];
Returns:
[1, 5, 9, 2, 6, 10, 3, 7, 11, 4, 8, 12]
The function i came up with:
convertList = (list) => {
let result = [];
let listTotalEntries = R.sum(R.map(R.length)(list));
let mod = R.modulo(R.__, list.length);
let counterRow = -1;
for (let i = 0; i < listTotalEntries; i++) {
if (mod(i) === 0) {
counterRow++;
}
if (list[mod(i)][counterRow]) {
result.push(list[mod(i)][counterRow]);
console.log(list[mod(i)][counterRow]);
}
}
console.log(result);
return result;
};
Question: This function works only with square matrices - how can i make it work with a variable length of the contained arrays?
Example:
let arr = [
[1, 2],
[],
[9, 10, 11, 12]
];
Should return:
[1, 9, 2, 10, 11, 12]
Thanks for your help!
Muff
You had a ramda.js tag in here. With Ramda, it's pretty simple, since there are two functions that will help:
const convertList = compose(flatten, transpose);
convertList(arr); //=> [1, 9, 2, 10, 11, 12]
transpose flips a matrix over its main diagonal, that is, changing rows to columns and vice versa. flatten turns a list of lists into a plain list. So composeing like this essentially creates the equivalent of list => flatten(transpose(list)).
You can see this in action on the Ramda REPL.
I suggest to go step-by-step through the arrays
var arr1 = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]],
arr2 = [[1, 2], [], [9, 10, 11, 12]];
function single(array) {
var r = [],
max = Math.max.apply(null, array.map(function (a) { return a.length; })),
i = 0, j,
l = array.length;
while (i < max) {
for (j = 0; j < l ; j++) {
i in array[j] && r.push(array[j][i]);
}
i++;
}
return r;
}
document.write('<pre>' + JSON.stringify(single(arr1), 0, 4) + '</pre>');
document.write('<pre>' + JSON.stringify(single(arr2), 0, 4) + '</pre>');
Did you try this simple one?
var singleDimensionArr = arr.reduce(function(prev,current){return prev.concat(current)});
For example
[
[1, 2],
[],
[9, 10, 11, 12]
].reduce(function(prev,current){return prev.concat(current)});
outputs [1, 2, 9, 10, 11, 12]
Edit:
Based on the inputs from OP below, since the concatenation needs to happen column wise
var max = Math.max.apply(null, arr.map(function (a) { return a.length; }));
var finalArr = []; for( var i = 0; i < max; i++)
{
for( var j = 0; j < arr.length; j++)
{
arr[j][i] ? finalArr.push(arr[j][i]) : "";
}
}
console.log(arr);
This example makes a big sparse array putting each item where it would belong if the array were square. Then it filters out null values which occur where no input item was present.
let arr = [
[1, 2],
[],
[9, 10, 11, 12]
];
var out = arr.reduce(function(o,n,i,a) {
for (var j=0;j<n.length;j++){
o[a.length * j + i] = n[j];
}
return o;
},[]).filter(function(n) {
return n !== null;
});
alert(JSON.stringify(out));