JS Reduce: sum specific position in a nested array of numbers - javascript

I want to reduce only a specific position in a nested number array
const array1 = [[1,2,3],[4,5,6],[7,8,9],[11,12,13]];
console.log(array1.reduce((prev, curr) => prev[2] + curr[2]));
The result is NaN, another solution?

1) You should use prev not prev[2] as
prev is of type number that you are returning not an array
2) If you are adding the number then it is better to take initial value as 0 as a second argument to the reduce method.
If you won't pass second argument, then reduce will take the array element at 0 index as the starting value i.e [1, 2, 3] and then if you add [1, 2, 3] + curr[2] then it will produce value as 1,2,36, which you are not expecting
const array1 = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
[11, 12, 13],
];
console.log(array1.reduce((prev, curr) => prev + curr[2], 0));

Related

how come I cannot do a Math.max on an array that has been sliced out of the another array

I am looking for a max number in each subarrays of an array. But when I did that it give me NaN. Why?
Let me outline what I've found. For context, I perform these tests in the console of Google Chrome.
Original array:
let arr = [[4, 5, 1, 3], [13, 27, 18, 26]];
I slice out the 1st subarray and assigned to arr1.
let arr1 = arr.slice(0, 1);
arr1;
[4, 5, 1, 3]
arr1[0]; //this is to see if I can get value at index 0
 [4, 5, 1, 3]
arr1.length;
1
When I perform the Math.max on arr1, I get NaN.
Math.max(...arr1);
NaN
When I couldn't get the Math.max value, I thought arr1 wasn't an array so I test to see if it is an array:
Array.isArray(arr1)
true
I was able to get the max number from the subarray using the original arry. My question is why I cannot get the Math.max on arr1, the array that sliced out of the original?
arr1 is an array of arrays, not an array of numbers. You can flatten the array before using Math.max. (Note: if you just want the ith subarray, just use arr[i] instead of slice. slice is only useful when you want multiple consecutive elements from an array.)
let arr = [[4, 5, 1, 3], [13, 27, 18, 26]];
let arr1 = arr.slice(0, 1);
console.log(JSON.stringify(arr1));
let max = Math.max(...arr1.flat());
console.log(max);
Your arr1 isn't [4, 5, 1, 3], it's [[4, 5, 1, 3]] — an array containing a single element, which is an array of numbers. slice creates an array containing the elements you've selected from the original array (just the first one in your case). That first element in arr is an array, so you end up with an array containing that array.
If you want to use arr1 as you've shown, just use arr[0], not arr.slice(0, 1):
let arr = [[4, 5, 1, 3], [13, 27, 18, 26]];
let arr1 = arr[0];
console.log(Math.max(...arr1));

Sorting two arrays according specific order

What I'm trying to do is ordering 2 arrays lets say...
let C = [10, 5, 6, 7]
let M = [8, 9, 2, 5]
The first array should stay as it is, but the second needs to be orderer so the output should go like this
[10, 5, 6, 7]
[9, 2, 5, 8]
Basically, i need to order the second array so that the max value matches the max value of the other array.
Please take into account that the first array should stay the same, so i cant reorder both, just the second
To clarify, each array item is a box with that amount of coins and multipliers. One array is coins and the other multipliers.
You can't change the position of the coin boxes, but you can move the multiplier so you can get the max amount of coins. But you can't move the coin boxes from their position.
What i've discover is that in order to get the max amount of coins, you need to multiply the highest possible value, with the highest posible value of the other table. so te correct order would be something like
[1,3,2,4]
[5,7,6,8]
and the values in example are
[5 3 7 1]
[1 4 3 9]
//expected output
[4 3 9 1]
You need to correlate the two arrays by matching the highest number from C to the highest at M, and so on until the smallest.
To do so create a new array of indexes (order), map arr1, add the index to each item, an then sort the array (I chose descending order).
Now clone arr2 and sort it in the same sort order you've used for C (descending order) to get the sorted array.
Now reduce the order array to another array, take the item with the same index i from sorted, and put it in the index idx taken from the order array.
const fn = (arr1, arr2) => {
const order = arr1
.map((n, i) => [n, i])
.sort(([n1], [n2]) => n2 - n1)
.map(([, i]) => i)
const sorted = [...arr2].sort((n1, n2) => n2 - n1)
return order.reduce((acc, idx, i) => (acc[idx] = sorted[i], acc), [])
}
console.log(JSON.stringify(fn(
[10, 5, 6, 7],
[8, 9, 2, 5]
))) // [9, 2, 5, 8]
// [2,0,1,3]
console.log(JSON.stringify(fn(
[5, 3, 7, 1],
[1, 4, 3, 9]
))) // [4, 3, 9, 1]
console.log(JSON.stringify(fn(
[5, 4],
[7, 2]
))) // [7, 2]
console.log(JSON.stringify(fn(
[11, 17, 39],
[7, 5, 3]
))) // [3, 5, 7]

How to multiply elements of an array by elements from another array with the same index?

I am trying to write an JS algorithm in which I have two arrays.
The value of the first one will have different numerical values. The second array will be constant, say for example [5, 3, 6, 8].
Now I would like to multiply the values from the first array, by the corresponding index value from the second array, so having for example such a first array: [3, 7, 2, 5] it would look like this: 5*3, 3*7, 6*2, 8*5.
From the result I would like to create a new array, which in this case is [15, 21, 12, 40].
How can I achieve this result?
You can use map() and use the optional parameter index which is the index of the current element being processed in the array:
const arr1 = [3, 4, 5, 6];
const arr2 = [7, 8, 9, 10];
const mulArrays = (arr1, arr2) => {
return arr1.map((e, index) => e * arr2[index]);
}
console.log(mulArrays(arr1, arr2));
This is assuming both arrays are of the same length.
You can simply use for loop -
var arr1 = [5, 3, 6, 8];
var arr2 = [3, 7, 2, 5];
var finalArr = [];
for (var i = 0; i < arr1.length; i++) {
finalArr[i] = arr1[i] * arr2[i];
}
console.log(finalArr);

Sorting an array of arrays of integers

I have a variable dimensions, which contains the maximum size of each element of an array, e.g.:
const dimensions = [10, 6, 4]
I also have an array of arrays containing as many integers as the size of the dimensions array, e.g.:
let boxes = [
[1, 2, 1],
[10, 2, 4],
[4, 1, 1],
[10, 2, 3]
]
For every array in boxes, no element will be higher than its counterpart in dimensions.
I want to find a way to sort these arrays, so that the sorted array boxes would be:
[
[1, 2, 1],
[4, 1, 1],
[10, 2, 3],
[10, 2, 4]
]
As you see, it's not just about sorting by the array's first element. It's sorting by first element, and if they're equal, the second, etc.
For each array of arrays, I have a related dimensions variable. But dimensions can be anything (also any length!) (and consequently, the arrays will have the same length of course).
I'm doing this in Javascript, but pseudocode is welcome too.
PS - This is not part of an assignment, I tried to abstract away most of the unnecessary stuff.
You can sort the values using Array.reduce to compare the values in each array being sorted, only updating the comparison result if it is currently 0 (i.e. the values up to now have been equal):
let boxes = [
[1, 2, 1],
[10, 2, 4],
[4, 1, 1],
[10, 2, 3]
]
boxes.sort((a, b) => a.reduce((c, v, i) => c ? c : v - b[i], 0));
console.log(boxes);

How to modify value of n dimensional array element where indices are specified by an array in Javascript

I have an n-dimensional array and I want to access/modify an element in it using another array to specify the indices.
I figured out how to access a value, however I do not know how to modify the original value.
// Arbitrary values and shape
arr = [[[8, 5, 8],
[9, 9, 9],
[0, 0, 1]],
[[7, 8, 2],
[9, 8, 3],
[9, 5, 6]]];
// Arbitrary values and length
index = [1, 2, 0];
// The following finds the value of arr[1][2][0]
// Where [1][2][0] is specified by the array "index"
tmp=arr.concat();
for(i = 0; i < index.length - 1; i++){
tmp = tmp[index[i]];
}
// The correct result of 9 is returned
result = tmp[index[index.length - 1]];
How can I modify a value in the array?
Is there a better/more efficient way to access a value?
This is a classic recursive algorithm, as each step includes the same algorithm:
Pop the first index from indices.
Keep going with the array that the newly-popped index points to.
Until you get to the last element in indices - then replace the relevant element in the lowest-level array.
function getUpdatedArray(inputArray, indices, valueToReplace) {
const ans = [...inputArray];
const nextIndices = [...indices];
const currIndex = nextIndices.shift();
let newValue = valueToReplace;
if (nextIndices.length > 0) {
newValue = getUpdatedArray(
inputArray[currIndex],
nextIndices,
valueToReplace,
);
} else if (Array.isArray(inputArray[currIndex])) {
throw new Error('Indices array points an array');
}
ans.splice(currIndex, 1, newValue);
return ans;
}
const arr = [
[
[8, 5, 8],
[9, 9, 9],
[0, 0, 1]
],
[
[7, 8, 2],
[9, 8, 3],
[9, 5, 6]
]
];
const indices = [1, 2, 0];
const newArr = getUpdatedArray(arr, indices, 100)
console.log(newArr);
You can change the values in array like this,
arr[x][y][z] = value;
Does this help?
I think what you're looking for is this:
arr[index[0]][index[1]][index[2]] = value;
I'm having trouble understanding what you're attempting to do in the second part of your example.

Categories

Resources