Looping through a nested array in JavaScript - 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);

Related

How to get three element after an particular index of a array?

I have two array
const array1 = [12, 13, 14, 15, 16, 17, 18, 19, 20]
const array2 = [17, 18]
I want to return first three element from array1 after comparing the index of array2 17 element or first element with the array1.
desired O/P from array1 after comparing is [14, 15, 16]
i have tried getting the index of the particular element.
const indexOf17FromArray1 = array1.indexOf(array2[0]) //5
just do array.slice((idx - 3), idx)
You can combine the use of array methods indexOf and slice.
First determine the last index (like you already have). Then based on your desired length modify it for use with slice. slice takes the start and end indices.
const array1 = [12, 13, 14, 15, 16, 17, 18, 19, 20];
const array2 = [17, 18];
const length = 3;
const indexOf17FromArray1 = array1.indexOf(array2[0])
console.log(array1.slice(indexOf17FromArray1 - length, indexOf17FromArray1));
You could get the index and check if -1 or subtract an offset and get a new array.
const
array = [12, 13, 14, 15, 16, 17, 18, 19, 20],
value = 17,
index = array.indexOf(value),
result = index === -1
? []
: array.slice(Math.max(index - 3, 0), index);
console.log(result);
Get the index of the element you want as reference.
const index = array1.indexOf(array2[0]);
If you want 3 elements after this index:
array1.slice(index + 1, index + 4);
If you want 3 elements before this index:
array1.slice(index - 3, index);
Finding the index of element = 17 in array1:
const array1 = [12, 13, 14, 15, 16, 17, 18, 19, 20];
const array2 = [17, 18];
const position17 = array1.findIndex(e => e === array2[0]);
The method findIndex will loop through array1 and check if the current element(e) is equal to array2[0].
Creating an array only with the three elements prior to element 17:
Here you will use the filter method, I'm passing the current value(item) and it's index. This method will check if the index is below "positon17" and if it is whitin the first three elements prior to element 17.
const newArray = array1.filter((item, index)=> (index < position17 & index >=position17-3)&& item);
console.log(newArray);
Here is a very simple function that will give you the next three after
your supplied index.
const array = [1,2,3,4,5,6,7,8,9];
const index = 2;
const threeElementsAfterIndex = [];
for( let i = 0; i < array.length; i++ ) {
if(i > index && i < index + 3) {
threeElementsAfterIndex.push(array[i]);
}
}
return threeElementsAfterIndex;
const array = [1, 2, 3, 4, 5, 6, 7, 8];
const index = 2;
console.log(array.slice(index + 1, index + 4));

Variable no asigned error in a index of a bidimensional array

I was trying to do a code Where i need use a bidimensional array and when i get it the index it say the variable isn't asigned
let vertices = [
[1, 10],
[2, 20],
[3, 30],
[1, 10],
];
for (let i = 0; i < vertices.length; i++) {
console.log(vertices[i][1]);
console.log(vertices[i + 1][0]);
}

How to count values inside an nested array in 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

JavaScript: Map issue

I have an issue with my code.
function openOrSenior(data) {
"use strict";
let myMap = new Map(data);
let test = [];
let old = [];
let val = [];
for(let key of myMap.keys()){
old.push(key);
}
for(let value of myMap.values()){
val.push(value);
}
for(let i = 0; i < data.length; i++){
if(old[i] >= 55 && val[i] > 7){
test.push("Senior");
} else { test.push("Open");}
}
return test;
}
If I have an input like this and debug my code:
openOrSenior([[21, 21], [0, 0], [90, 8], [1, 1], [60, 12], [90, 7], [75, 11], [55, 10], [90, 9], [54, 9]]);
My map have this key&value pairs :myMap
It's not in the right sequence and does not contain all key-->values pairs, but if I take a subset of my input like this:
openOrSenior([[21, 21], [0, 0], [90, 8]]);
The Code does what I want:Here is the picture
What am I doing wrong?
Best Regards
As I commented above, a Map has unique keys. You can however extend the Map class and create a Multimap. A very (very very) simple implemantation is found below. Below will add all the values to an array found at key, pushing to the existing value if the key is already in our Multimap, you can add elements by using set()
class Multimap extends Map {
constructor(arrOfArr = [[]]) {
super(arrOfArr);
}
set(key, value) {
super.set(key, super.has(key) ? super.get(key).concat(value) : [value]);
}
}
let foo = new Multimap([[21, 21], [0, 0], [90, 8], [1, 1], [60, 12], [90, 7], [75, 11], [55, 10], [90, 9], [54, 9]]);
foo.set(21, 22);
for (let [k,v] of foo.entries()) {
console.log(k, v);
}

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