how to iterate through nested array items separately - javascript

I have a three-dimensional array, for example:
var array = [[1,0][3,3][2,1][0,8]]
and I want to do something with the first item in each sub-array, but something else with the second item in each sub-array.
So, for example, I would like to find the sum of array[0][0], array[1][0], array[2][0] and so on for array.length. But, I would like a separate result for array[0][1], array[1][1], array[2][1], etc.
I'm still learning javascript (very slowly) and, if possible, I would like to be pointed in the right direction, rather than getting a ready-made solution. I've been looking for possible solutions, and I think I may need a nested for loop, but I'm not sure how to structure it to get all the values.
I've been trying something along the lines of:
for (var i = 0; i < array.length; i++) {
for (var j = 0; j < array.length; j++) {
return array[i][j];
}
}
but I don't understand what's happening well enough to manipulate the result.
If anyone could steer me in the right direction toward finding a solution, that'd be much appreciated.
Thanks in advance.

You might consider using .reduce - on each iteration, add the first array value to a property of the accumulator, and do whatever you need to with the second array value, assigning its result to another property of the accumulator. For example, let's say for the second items, you wanted to get their product:
const input = [[1,0],[3,3],[2,1],[0,8]];
const { sum, product } = input
.reduce(({ sum=0, product=1 }, [item0, item1]) => ({
sum: sum + item0,
product: product * item1
}), {});
console.log(sum, product);
In the above code, the accumulator is an object with two properties, sum (starts at 0) and product (starts at 1). Inside the reduce, an object is returned, with the new sum being the old sum plus the first item in the array, and with the new product being the old product multiplied by the second item in the array. (of course, the resulting product is 0 because in the first sub-array, the second item is 0)
Also note that arrays always need commas separating each array item - you need to fix your input array's syntax.
Of course, you can also for loops if you have to, but I think array methods are preferable because they're more functional, have better abstraction, and don't require manual iteration. The same code with a for loop would look like this:
const input = [[1,0],[3,3],[2,1],[0,8]];
let sum = 0;
let product = 1;
for (let i = 0; i < input.length; i++) {
const [item0, item1] = input[i];
sum += item0;
product *= item1;
}
console.log(sum, product);

You just need one for-loop since you just have one array with arrays inside where you know the indexes you want to proccess. So it would be something as follows:
let sum1 = 0;
let sum2 = 0;
for(let i = 0; i < array.length; i++) {
sum1 += array[i][0];
sum2 += array[i][1];
}
console.log('sum1: ', sum1);
console.log('sum2: ', sum2);

Firstly the array you have posted is a 2d array not a 3d array.
And the nested for loop you have posted is perfect for what you want.
Your first for statment is looping through the the frist deminsion of your array. the second is getting each index in the second array
var array = [[1,0],[3,3],[2,1],[0,8]]
for (var i = 0; i < array.length; i++) {
//This loop over these [1,0],[3,3],[2,1],[0,8]
//So i on the first loop is this object [1,0] so so on
for (var j = 0; j < array.length; j++) {
//This will loop over the i object
//First loop j will be 1
//Here is where you would do something with the index i,j.
//Right now you are just returning 1 on the first loop
return array[i][j];
}
}
I hope this help your understanding

Since you asked for help with pointing you in the right direction, I would suggest you start with simple console.logs to see what's happening (comments are inline):
var array = [[1, 0],[3, 3],[2, 1],[0, 8]];
var results = [0, 0]; // this array is to store the results of our computation
for (var i = 0; i < array.length; i++) { // for each subarray in array
console.log('examining subarray ', array[i]);
for (var j = 0; j < array[i].length; j++) { // for each element in subarray
if (j === 0) {
console.log('... do something with the first element of this array, which is: ' + array[i][j]);
results[j] += array[i][j]
} else if (j === 1) {
console.log('... do something with the second element of this array, which is: ' + array[i][j]);
// do some other computation and store it in results
}
}
}
console.log('Final results are ', results);

You made a mistake on the second line. You need to iterate through the nested array and then take the value from the main array.
const mainArray = [[1, 0], [3, 3], [2, 1], [0, 8]];
for (let i = 0; i < mainArray.length; i++) {
const nestedArray = mainArray[i]
for (let j = 0; j < nestedArray.length; j++) {
const value = mainArray[i][j]
switch(j) {
case 0:
console.log(`first item of array number ${i+1} has value: ${value}`)
break;
case 1:
console.log(`second item of array number ${i+1} has value: ${value}`)
break;
}
}
}

You can use a for...of loop along with destructuring like so:
for(let [a, b] of array) {
// a will be the first item from the subarrays: array[0][0], array[1][0], ...
// b will be the second: : array[0][1], array[1][1], ...
}
Demo:
let array = [[1, 0], [3, 3], [2, 1], [0, 8]];
for(let [a, b] of array) {
console.log("a: " + a);
console.log("b: " + b);
}

Using a debugger within your loop would be a good way to watch and understand each step of the loop
Using the forEach method would be a clearer approach to loop through the array and its children
const items = [[1, 0],[3, 3],[2, 1],[0, 8]]
let results = {}
items.forEach((item, index) => {
// debugger;
item.forEach((subItem, subIndex) => {
// debugger;
if (results[subIndex]) {
results[subIndex] = results[subIndex] + subItem
} else {
results[subIndex] = subItem
}
})
})
console.log(results) // { 0: 6, 1: 12 }
// *********EXPLANATION BELOW ************
const items = [[1, 0],[3, 3],[2, 1],[0, 8]]
// store results in its own key:value pair
const results = {}
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach
// forEach is a more readable way to loop through an array
items.forEach((item, index) => {
// use console.log(item, index) to see the values in each loop e.g first loop contains `item = [1,0]`
// you can also use a debugger here which would be the easiest way to understand the iteration
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/debugger
// debugger;
// loop over item (e.g [1,0]) to get subItems and their index
item.forEach((subItem, subIndex) => {
// get the result from previous sums from `result`
// and add them to the current subItem values
// if there was no previous sum(i.e for first entry)
// use subItem as the first value.
if (results[subIndex]) {
results[subIndex] = results[subIndex] + subItem
} else {
results[subIndex] = subItem
}
// Below is a oneliner way to do line 16 to 20 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator
// results[subIndex] = results[subIndex] ? results[subIndex] + subItem : subItem
})
})
console.log(results) // { 0: 6, 1: 12 } the results of `array[0][0],array[1][0]...` are in 0 and the result of `array[0][1], array[1][1]...` are in 1 and so on.

Obligatory one-liner to bake your noodle.
console.log([[1, 0], [3, 3], [2, 1], [0, 8]].reduce((p, c) => [p[0] += c[0], p[1] += c[1]]));

Related

Remove Duplicates from Sorted Array (different final results)

I am new at Programing and learning Javascript by doing some exercises from leetcode.com.
I wanted to write a code to remove duplicates in a sorted array.
When I use "console.log" at the end of the function to show the final result, I get the expected result. However when I use return (with the same variable) I get a wrong result. Can anybody please tell me, where I went wrong?
Hier is my code:
/**
* #param {number[]} nums
* #return {number}
*/
var removeDuplicates = function (nums) {
var newNums = []
if (nums.length == 0) {
newNums = []
}
for (var i = 0; i < nums.length; i++) {
var curr = nums[i]
var next = nums[i + 1]
if (curr != next) {
newNums.push(curr)
}
}
console.log(newNums)
return newNums
};
And here is a picture with the code and the results. the green arrow shows the output of (console.log), and the red one shows the output of (return).
Thank you in advance!
A slightly different approach by keeping the original object reference to the array and mutating the array by copying and adjusting the length of the array.
This approach does not need another array.
It basically checks if the predecessor is unequal to the actual item and copies the item to a new index j. This variable has the final length of the array and truncates the unwanted rest of the array.
function removeDuplicates(array) {
let j = 0;
for (let i = 0; i < array.length; i++) {
if (array[i - 1] !== array[i]) array[j++] = array[i];
}
array.length = j;
return array;
}
console.log(removeDuplicates([0, 1, 1, 2, 2, 2, 2, 3, 4, 5, 5]));
Here's how you can remove duplicates in any(sorted or unsorted) array in Javascript
const removeDuplicates = (orignalArray) =>{
let allUniqueArray=[];
let repWordArray=orignalArray.slice();
const removeAnElement=(array, elem)=>{
const index = array.indexOf(elem);
if (index > -1) {
array.splice(index, 1);
}
return array;
}
orignalArray.forEach(elem=>{
if(!allUniqueArray.includes(elem)){
allUniqueArray.push(elem);
repWordArray=removeAnElement(repWordArray,elem)
}
});
return allUniqueArray;
};
let array=[1,2,3,3,4,5,6,6,7];
const uniqueArray = removeDuplicates(array);
console.log('array: ',array);
console.log('uniqueArray: ',uniqueArray);

remove specified value from array [duplicate]

This question already has answers here:
How can I remove a specific item from an array in JavaScript?
(142 answers)
Closed 1 year ago.
How can I check whether an array contains a value, and if so, remove it?
PS: For this exercise, I'm not allowed to use anything more than than .pop, .push and .length array functions.
My logic is the following: if the specified value is within the array, reorder the array so that the last element of it will contain this value, then remove it with .pop. But how can I find this value and reorder it without using anything more than those array functions I specified above?
This is what I managed to come up with so far:
let array_1 = [1,2,3];
if (array_1 == 2){
//reorder somehow
array_1.pop();
}
console.log(array_1);
Using this approach, you are not creating a new array but modifying it. It uses .pop().
let array_1 = [1, 2, 3];
// Iterate all array
for (let i = 0; i < array_1.length; i++) {
// While there is a 2 element in the actual index, move all elements (from i index) to the previous index
while(array_1[i] === 2) {
for (let j = i; j < array_1.length - 1; j++) {
array_1[j] = array_1[j + 1];
}
// Now remove the last element (since we move all elements to the previous index)
array_1.pop();
}
}
console.log(array_1);
Here a snippet so you can try it
let array_1 = [1, 2, 3, 4, 2, 5, 2, 6, 2];
for (let i = 0; i < array_1.length; i++) {
while(array_1[i] === 2) {
for (let j = i; j < array_1.length - 1; j++) {
array_1[j] = array_1[j + 1];
}
array_1.pop();
}
}
console.log(array_1);
This would mantain the order of the array, but without the "2" elements.
Here's another option using pop
const filter = (array, target) => {
const newArray = [];
let tmp;
while(tmp = array.pop()) {
if (tmp !== target) {
newArray.push(tmp)
}
}
console.log(newArray)
return newArray;
}
filter([1,2,3,4], 2) // [4, 3, 1] Note that it reversed the order of the array!
If you are limited to pop, push and length, you can loop over all elements, check if a given element matches the value you are looking for, and add them to a new array using push.
let array_1 = [1,2,3];
let newArray = [];
for (let i = 0; i < array_1.length; i++) {
if (array_1[i] !== 2) {
newArray.push(array_1[i]);
}
}
console.log(newArray);
// using splice
// splice(indexStart, how many, replace with)
// example :
let arr = [0,1,2,3,4,5];
// remove at index 1
arr.splice(1,1);
console.log( arr );
// replace at index 1
arr.splice(1,1,"new 1");
console.log( arr );
// merge index 2 and 3
arr.splice(2,2,"merge 2 and 3");
console.log( arr );
// create 2 new items start at index 2
arr.splice(2,2,"new 2", "new 3");
console.log( arr );

HackerRank - Minimum Swaps 2 Timeout

This challenge asks that you find the minimum number of swaps to sort an array of jumbled consecutive digits to ascending order. So far my code passes most of the tests, however there are four that fail due to timeout. Could anyone explain why my code is timing out? Is there a way to make it find an answer faster?
function minimumSwaps(arr) {
const min = Math.min(...arr);
let swapCount = 0;
const swap = (array, a, b) => {
let test = array[a];
array[a] = array[b];
array[b] = test;
}
for(let i=0; i<arr.length; i++){
if(arr[i]!==i+min){
swap(arr, i, arr.indexOf(i+min));
swapCount++;
}
}
return swapCount;
}
I thought it was a good solution since it only has to iterate over the length of the array once? I'd love to be able to understand why this isn't performing well enough
Your big issue is with the call to arr.indexOf, as that has to scan the entire array each time you do a swap. You can work around that by generating a reverse lookup from value to array index before starting to sort, and then maintaining that list during the sort. Note that you don't need to do a full swap, only copy the value from arr[i] to its correct place in the array since you don't revisit a number once you have passed it. Also you don't need min, as under the conditions of the question it is guaranteed to be 1, and you don't need to look at the last value in the array since by the time you get to it it has to be correct.
function minimumSwaps(arr) {
const indexes = arr.reduce((c, v, i) => (c[v] = i, c), []);
const len = arr.length - 1;
let swapCount = 0;
for (let i = 0; i < len; i++) {
if (arr[i] !== i + 1) {
arr[indexes[i+1]] = arr[i];
indexes[arr[i]] = indexes[i+1];
swapCount++;
}
}
return swapCount;
}
console.log(minimumSwaps([7, 1, 3, 2, 4, 5, 6]));
console.log(minimumSwaps([4, 3, 1, 2]));
console.log(minimumSwaps([2, 3, 4, 1, 5]));
console.log(minimumSwaps([1, 3, 5, 2, 4, 6, 7]));
I think we should flip function not search function.
function minimumSwaps($arr) {
$outp = 0;
$result = array_flip($arr);
for($i=0; $i<count($arr); $i++){
if($arr[$i] != $i +1){
$keyswp = $result[$i + 1];
$temp = $arr[$i];
$arr[$i] = $i + 1;
$arr[$keyswp] = $temp;
$tempr = $result[$i + 1];
$result[$i + 1] = $i +1;
$result[$temp] = $keyswp;
$outp = $outp + 1;
}
}
return $outp;
}
Here is my solution , it is similar to Nick's except instead of the Array.Proptytype.indexOf method I used an object literal to map the indices of each value for a better Time complexity since search in object literal is O(1) (You can use ES6 maps too). Here is the code
function minimumSwaps(arr) {
let count = 0;
let search = arr.reduce((o, e, i) => {
o[e] = i
return o
}, {})
for(let i =0 ; i < arr.length - 1; i++){
let j = search[i+1]
if(arr[i] !== i+1) {
[arr[i], arr[j]] = [arr[j], arr[i]]
search[arr[i]] = i;
search[arr[j]] = j;
count += 1
}
}
console.log(arr)
return count
}
As suggested by others, you shouldn't use the indexOf method as it makes your solution O(n^2) (As the indexOf method has to scan the entire array again). You can create a position map array before hand and use it later during the swap. It will keep your solution linear. Here is the detailed explanation and solution to the HackerRank Minimum Swaps 2 Problem in java, c, c++ and js, using this method.

Javascript: Increment array element in for loop when working with nested for loops & two dimensional arrays

I have an array of arrays that looks like this:
matrix = [[0,1,1,2], [0,5,0,0], [2,0,3,3]]
I wanted to iterate through this nested array and compare elements from each array to their counterpart in the other arrays i.e. compare the 5 (1th element) in the second array to the 1 (1th element) in the first array and the 0 (1th element) in the third array. I want to check if the element in the current array I'm looking at has a counterpart in one of the other arrays that equals 0.
So basically I want to compare [0][0] to [1][0] and [2][0], [0][1] to [2][1] and [3][1], and so forth, in a nested for loop.
Here's what I tried:
function matrixElementsSum(matrix) {
let total = 0;
let arr = [];
for(let i = 0; i < matrix.length; i++) {
for(let j = 0; j < matrix[i].length; j++) {
if(matrix[i][j] != 0 && matrix[i + 1][j] != 0) {
console.log(matrix[i][j]);
}
}
}
}
This part of the if statement results in an undefined error :
&& matrix[i + 1][j] != 0
In a regular array/for loop we can increment the i to compare the current element to the next element. How can I do this in a nested for loop when working with an array of arrays?
If the subarrays are of the same length you only have to iterate over the first subarray's elements and compare it to the their counterparts, If i understand you correctly i think this will do it for you:
var matrix = [[0,1,1,2], [0,5,0,0], [2,0,3,3]]
var len = matrix[0].length
var flatArray = matrix.flat()
for(let index=0;index<len;index++){
if(flatArray[index] !== 0 && flatArray[index + len] !== 0 && flatArray[index
+ 2*len] !== 0)
console.log(index,flatArray[index])
}
Instead of nested loops, you can use the ES6 iteration protocol and grab all iterators from internal arrays, then consume their output until finished. This can simplify how you work with the data because each iteration you only have the the current sequential item from each array:
function compareAll(matrix) {
//get all the iterators for sub-arrays
const iterators = matrix.map(sub => sub[Symbol.iterator]());
while(true) {
//advance all iterators and take theur results
let res = iterators.map(it => it.next());
//terminate if any is done
if (res.some(r => r.done)) break;
//get the values
let currentValues = res.map(({value}) => value);
//do something with them
const allEqual = currentValues.every(function(value) {
return value === this;
}, currentValues[0]);
console.log(currentValues, allEqual);
}
}
compareAll([[0, 1, 1, 2], [0, 5, 0, 0], [2, 0, 3, 3]]);

compare elements of array of many arrays

I trying to loop through an array of arrays, and compare the elements with each-other in-order to find the common elements. so lets say if we have var arr = [[1,2,3],[4,2,5]]; I want to first compare [i][i] and [i+1][i], [i][i+1] and [i+1][i+1] and [i][i+2] and [i+1][i+2] and so on. here is my code:
function sym(args) {
var fullArr = [];
var finalArr = [];
// store the arguments inside a single array
for (var count = 0; count < arguments.length; count ++) {
fullArr[count] = arguments[count];
}
// loop through finalArr[];
for (var i = 0; i < fullArr.length; i++) {
if (fullArr[i][i] == fullArr[i++][i++]) {
// if the element matches (it is a common element)
// store it inside finalArr
finalArr[i] = fullArr[i];
}
}
return finalArr;
}
sym([1, 2, 3], [5, 2, 1, 4]);
problem: when I run the code instead of an array containing the matching element, I get an empty array
You first have to iterate over one array and see if the other array includes the value you have specified.
My answer is similar to a nested for loop in that the includes method does exactly that. It takes in as a parameter an element and checks if the array which called it contains said element. In order to do that it must iterate through all elements in the array in the worst case.
My answer also assumes that you only want to count duplicate matches once.
function sym(args) {
var fullArr = [];
var finalArr = [];
// store the arguments inside a single array
for (var count = 0; count < arguments.length; count ++) {
fullArr[count] = arguments[count];
}
// loop through finalArr[];
//since you are comparing only two arrays in this
//example you just have to iterate over each element in the first array aka fullArr[0] and
//check if each element "e" is also in the second array aka fullArr[1]
//AND that your final output array does not already contain it.
//If both of these are true then we push the element to the output array.
fullArr[0].forEach(function(e){
if(fullArr[1].includes(e) && !finalArr.includes(e)) finalArr.push(e);
});
return finalArr;
}
sym([1, 2, 3], [5, 2, 1, 4]);
However if you want to check if a particular element exists in all collections of an n length array then I would propose something like this:
function sym(args) {
var fullArr = [];
var finalArr = [];
// store the arguments inside a single array
for (var count = 0; count < arguments.length; count ++) {
fullArr[count] = arguments[count];
}
var newArr = fullArr[0].reduce( function(prev, e1) {
if(prev.indexOf(e1) < 0 && fullArr.every( function(arr){
return arr.indexOf(e1) > -1;
})){
return [...prev, e1];
}else{
return prev;
};
},[]);
alert(newArr);
return newArr;
}
sym([1,1, 2, 3,4], [5, 2, 1, 4], [4,1,2, 5]);
You can iterate over the first array and check if any of its values are common through all the other arrays.
function sym() {
var common = [];
for (var i=0; i<arguments[0].length; i++) {
var isCommon = common.indexOf(arguments[0][i]) === -1; // first check if its not already exists in the common array
for (var j=1; j<arguments.length && isCommon; j++) {
isCommon = arguments[j].indexOf(arguments[0][i]) > -1
}
if (isCommon) common.push(arguments[0][i])
}
return common;
}
of course you can improve it by iterating over the smallest array.
In your code, when the following line executes, you also increment the value of i which is your control variable:
if (fullArr[i][i] == fullArr[i++][i++])
Thus, this is how your i variable gets incremented in each iteration:
Iteration #1: i = 0
Iteration #2: i = 3
- you get i+2 from the line that I mentioned above, +1 more from the increment that you specify in the final condition of the for loop
Therefore, even after the first iteration, your function will return an empty array on your particular scenario, as you are passing an array of length 3, and the for loop ends after i = 0 on the first iteration.
Even if the loop would go on, it would return an index out of bounds exception because your array of length 3 would not have an array[3] element.
For example, if you want to compare just two arrays, as in your scenario, you need to loop through each of them and compare their elements:
function sym(array1, array2) {
var results = [];
for (var i = 0; i < array1.length; i++) {
for (var j = 0; j < array2.length; j++) {
if(array1[i] === array2[j]) {
if(results.indexOf(array1[i]) === -1) {
results.push(array1[i]);
}
}
}
}
return results;
}
sym([1, 2, 3], [5, 2, 1, 4]);
I have also built a solution that returns the intersection of the arrays that you provide as the parameters for the function, regardless of how many arrays there are:
function sym(args) {
var paramSet = Array.prototype.slice.call(arguments);
var counterObject = {};
var results = [];
paramSet.forEach(function (array) {
// Filter the arrays in order to remove duplicate values
var uniqueArray = array.filter(function (elem, index, arr) {
return index == arr.indexOf(elem);
});
uniqueArray.forEach(function (element) {
if (Object.prototype.hasOwnProperty.call(counterObject, element)) {
counterObject[element]++;
} else {
counterObject[element] = 1;
}
});
});
for (var key in counterObject) {
if (counterObject[key] === paramSet.length) {
results.push(parseInt(key));
}
}
return results;
}
sym([1, 2, 3, 3, 3], [5, 2, 1, 4], [1, 7, 9, 10]);
The above code will return [1] for the example that I provided, as that is the intersection of all 3 arrays.

Categories