How to count values inside an nested array in Javascript - javascript

I have an nested array as below:
[
["States", "Count"],
["DISABLE", 13],
["DENY", 9],
["FAULTY", 11],
["OFF", 8],
["ON", 20]
];
I want to get the count of all the values inside the nested array's 'count' column.
the returning result should be like:61 (13+9+11+8+20)
Is there any way to do this in Javascript/react?

You can use reduce() to find the sum like below code. Before doing that make sure you removed the first one in your array, because it's a string. I am using shift() to remove it. Instead of shift() you can use splice().
var a = [
["States", "Count"],
["DISABLE", 13],
["DENY", 9],
["FAULTY", 11],
["OFF", 8],
["ON", 20]
];
a.shift(); // removing first element
var total = a.reduce((sum, item) => sum+=item[1], 0);
console.log(total);

If you can change the data structure, you probably want to have something like :
{
'DISABLE': 13,
'DENY': 9,
...
}
If you can't, this should work :
const count = array.reduce((acc, cur) => acc += cur[1], 0);

const countArr = [
["DISABLE", 13],
["DENY", 9],
["FAULTY", 11],
["OFF", 8],
["ON", 20]
]
const sum = countArr.reduce((firstParam, secondParam) => {
const [name, count ] = secondParam
return firstParam + count
}, 0) // 61
remove your first element in array then try this

Related

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

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));

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);

Looping through a nested array in JavaScript

Presently I have a multidimensional array that I want to loop over. All I want is to push the inner elements to an empty array. But What I'm getting is totally different from the expected output.
All have done so far below
const prices = [ [2, 20], [7, 50], [12, 100], [17, 40], [22, 32], [27, 25 ] ];
function addItemToCart() {
let new_items = [] // I want this array to be [2, 7, 12, 17, 22, 27]
// looping outer array elements
for(let i = 0; i < prices.length; i++) {
for(let j = 0; j < prices[i].length; j++) {
new_items.push(prices[i][j])
console.log(new_items);
}
}
}
addItemToCart()
Use map: const newItems = prices.map(price => price[0])
Do you want to completely flatten your array, or just take the first item from each inner array and copy that to the new array?
If you want to flatten it completely, you can do it like this:
const newArray = prices.reduce((res, arr) => [...res, ...arr], []);
If you only want the first item from each inner array, I would recommend the solution that Konstantin suggested.
You don't need loops for that:
const prices = [ [2, 20], [7, 50], [12, 100], [17, 40], [22, 32], [27, 25 ] ];
const toAdd = [].concat.apply([], prices);
console.log(toAdd);

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.

Creating a 2d array that consisted of another 2d array's acumulation

I have an array which is like that: [[0, 50], [1, 40], [2, 30], [3, 20], [5, 10]]
And I want to accumulative the second values: [[0, 50], [1, 90], [2, 120], [3, 140], [5, 150]]
I tried the code part below which works for one dimensional arrays, but it doesn't work for 2d arrays. Is it possible to accumulate it by using reduce function? Or is there different way to do it?
var array1 = [[0, 50], [1, 40], [2, 30], [3, 20], [5, 10]];
var newArray1 = [];
array1.reduce(
function (previousValue, currentValue, currentIndex) {
return newArray1[currentIndex] = [currentIndex, (previousValue[1] + currentValue[1])];
}, 0
);
You can use map() with optional thisArg parameter
var array1 = [[0, 50], [1, 40], [2, 30], [3, 20], [5, 10]];
var result = array1.map(function(e) {
this.num = (this.num || 0) + e[1];
return [e[0], this.num];
}, {});
console.log(result);
Use Array#reduce method
var array1 = [
[0, 50],
[1, 40],
[2, 30],
[3, 20],
[5, 10]
];
// initialize as the array of first element in original array
var newArray1 = [array1[0].slice()];
array1
// get remaining array element except first
.slice(1)
// iterate over the array value to generate result array
.reduce(function(arr, v, i) {
// copy the array element if you don't want to refer the old
v = v.slice();
// add previous array value
v[1] += arr[i][1];
// push updated array to result array
arr.push(v);
// retur the updated array
return arr;
// set initial value as array which contains first element(array) copy
},newArray1);
console.log(newArray1)
UPDATE 1: Another method with less code
var array1 = [
[0, 50],
[1, 40],
[2, 30],
[3, 20],
[5, 10]
];
var newArray1 = [array1[0].slice()];
array1.slice(1).reduce(function(arr, v, i) {
arr.push([v[0], v[1] + arr[i][1]]);
return arr;
}, newArray1);
console.log(newArray1)
UPDATE 2 : Much more reduced version without using Array#slice method.
var array1 = [
[0, 50],
[1, 40],
[2, 30],
[3, 20],
[5, 10]
];
var newArray1 = array1.reduce(function(arr, v, i) {
// push value to array add value only if `arr` contains any element
arr.push([v[0], v[1] + (arr.length && arr[i - 1][1])]);
return arr;
// set initial value as an empty array
}, []);
console.log(newArray1)
Just for fun lets invent a new array functor, Array.prototype.extend() This works like opposite to the reduce. It takes an array and extends it starting from the last item by utilizing a provided callback. When the callback returns undefined it sops extending. Let see how we can have fun with it in this particular case;
Array.prototype.extend = function(cb){
var len = this.length + 1,
res = cb(this[len-1], len-1, this);
return res ? this.extend(cb) : this;
};
var arr = [[0, 50], [1, 40], [2, 30], [3, 20], [5, 10]],
cb = function(e,i,a){
return i === 0 ? a.push(arr[i])
: i < arr.length ? a.push([arr[i][0], arr[i][1] + a[i-1][1]])
: void 0;
};
result = [].extend(cb);
console.log(result);

Categories

Resources