I have a nested array:
let array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
I need to iterate over the first and second element of every nested array and update the changes on the original array. How do I achieve this? I have tried many options but the results don't update the original array. For example:
let arrayCop = [];
for (let i = 0; i <= 1; i++) {
for (let j = 0; j <= 1; j++) {
arrayCop.push(array[i][j]);
}
}
arrayCop.forEach(...);
Thanks.
This is my full code, I'm trying to build a legal sudoku generator:
let sudoku = [];
function populateSudoku() {
let array = [];
while (array.length <= 8) {
let randomNum = Math.floor(Math.random() * 9 + 1);
array.push(randomNum);
if (array.indexOf(randomNum) < array.lastIndexOf(randomNum)) {
array.pop()
}
}
return array;
}
while (sudoku.length <= 8) {
sudoku.push(populateSudoku());
}
for (let i = 0; i < sudoku.length; i++) {
for (let j = 0; j < sudoku.length; j++) {
sudoku[i].forEach(element => {
if (sudoku[i].indexOf(element) === sudoku[j].indexOf(element) &&
(i !== j)) {
sudoku[j][sudoku[i].indexOf(element)] = 0;
}
})
}
}
let array = [];
for (let i = 0; i <= 2; i++) {
for (let j = 0; j <= 2; j++) {
array.push(sudoku[i][j]);
}
}
array[3] = 452345;
console.log(sudoku);
**
# I did it! #
**
let array = [[1, 2, 3], [7, 4, 1], [2, 4, 3]];
// checks for duplicates just in first and second item of every file
for (let i = 0; i <= 1; i++) {
for (let j = 0; j <= 2; j++) {
array[i].forEach((element, index) => {
if ((i !== j) && index <= 1 &&
(array[j].indexOf(element) >= 0 && array[j].indexOf(element) <= 1)) {
array[i][index] = 'x';
}
})
}
}
console.log(array);
If I understand right, you would like to change the original array to:
[[1, 2], [4, 5], [7, 8]]
If so, this would do it:
array.forEach(element => element.splice(2))
You can use Array.prototype.map function
ORIGINAL
I need to iterate over the first and second element of every nested
array and update the changes on the original array
function iterate(array) {
array.forEach(function(element, index) {
console.log('[' + index + "][0]", element[0]);
console.log('[' + index + "][1]", element[1])
})
}
Not sure what you mean by update changes to the original array, though...
EDIT
Alright, after looking through other answers, I believe #NinaW got what you were looking for.
function parse(array) {
array.forEach(function(element) { element.slice(0, 2) })
}
Use flatMap and destructuring.
let array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
let arrayCop = array.flatMap(([first, second]) => [first, second]);
console.log(arrayCop)
let array = [[1, 2, 3], [7, 4, 1], [2, 4, 3]];
console.log(array);
// checks for duplicates just in first and second item of every file
for (let i = 0; i <= 1; i++) {
for (let j = 0; j <= 2; j++) {
array[i].forEach((element, index) => {
if ((i !== j) && index <= 1 &&
(array[j].indexOf(element) >= 0 && array[j].indexOf(element) <= 1)) {
array[i][index] = 'x';
}
})
}
}
console.log(array);
Related
The input is an array ints [11, 2, 7, 8, 4, 6] and and integer s 10. The function is to output an array with a pair of two numbers from ints which first form a sum of 10. So here the output should be [2, 8], because 2 + 8 = 10. Why does it output empty array? The arrResults was updated in the nested for loop, so why doesn't it show up like that after the final return statement?
function sumPairs(ints, s) {
let arrResults = [];
let sumOfTwo;
for (i = 0; i < ints.length; i++) {
for (j = 0; j < ints.length; j++) {
sumOfTwo = ints[i] + ints[j];
if (sumOfTwo === s) {
arrResults.push(ints[i]);
arrResults.push(ints[j]);
break;
}
}
if (arrResults !== []) {
break;
}
}
return arrResults;
}
console.log(sumPairs([11, 2, 7, 8, 4, 6], 10));
Beside the wrong comparing of an array with another array (without having the same object reference)
a = []
b = []
a === b // false
// other example
a = []
b = a
a === b // true
for checking the length,
a = []
a.length // 0
and by using a nearly quadratic time complexity of n², even with looping
i = 0; i < array.length - 1
j = i + 1; j < array.length
which is more then the half of n², but strill quadratic,
you could take a single loop with an object fo already seen values.
This approach finds the first pair of the array for a certain sum.
function sumPairs(ints, s) {
const needed = {};
for (const value of ints) {
if (needed[value]) return [s - value, value];
needed[s - value] = true;
}
}
console.log(sumPairs([11, 2, 7, 8, 4, 6], 10));
Your code fails because you are checking to see if the array is empty. The problem is that check is never going to be false, so it exits on the first iteration.
console.log([]===[]);
console.log([]!==[]);
So code with changes to improve performance and to exit out
function sumPairs(ints, s) {
let arrResults = [];
let sumOfTwo;
for (let i = 0; i < ints.length; i++) {
for (let j = i + 1; j < ints.length; j++) {
sumOfTwo = ints[i] + ints[j];
if (sumOfTwo === s) {
arrResults.push(ints[i]);
arrResults.push(ints[j]);
break;
}
}
if (arrResults.length) {
break;
}
}
return arrResults;
}
console.log(sumPairs([11, 2, 7, 8, 4, 6], 10));
There is no need to break out twice, just return the array
function sumPairs(ints, s) {
let arrResults = [];
let sumOfTwo;
for (let i = 0; i < ints.length; i++) {
for (let j = i + 1; j < ints.length; j++) {
sumOfTwo = ints[i] + ints[j];
if (sumOfTwo === s) {
return [ints[i], ints[j]];
}
}
}
return null;
}
console.log(sumPairs([11, 2, 7, 8, 4, 6], 10));
function arrayDiff(a, b) {
let result = [];
for (let i = 0; i < a.length; i++) {
for (let j = 0; j < b.length; j++) {
if (a[i] !== b[j]) {
result.push(a[i]);
}
}
}
return result;
}
console.log(arrayDiff([1,2,2,3], [1])); // output: [2,2,3]
console.log(arrayDiff([1,2,2,3], [1,2])); // output: [1,2,2,3,3] // desired output: [3]
Trying to solve Array Difference, multiple items inside 'b' causing unwanted output.
Consider using a Set and Array#filter.
const
arr1 = [1, 5, 3, 7, 9],
arr2 = [5, 1, 10, 13],
s = new Set(arr2),
res = arr1.filter((a) => !s.has(a));
console.log(res);
I'm having issues with leetcode algo question 1252. I'm not sure why but my for loop seems to run twice. The question is:
"Given n and m which are the dimensions of a matrix initialized by zeros and given an array indices where indices[i] = [ri, ci]. For each pair of [ri, ci] you have to increment all cells in row ri and column ci by 1.
Return the number of cells with odd values in the matrix after applying the increment to all indices."
var oddCells = function(n, m, indices) {
let matrix = [];
let array = Array(m).fill(0);
let k = 0;
while (k < n) {
matrix.push(array);
k++;
}
for (let i = 0; i < indices.length; i++) {
const row = indices[i][0];
const col = indices[i][1];
for (let j = 0; j < n; j++) {
matrix[j][col]++;
}
for (let i = 0; i < m; i++) {
matrix[row][i]++;
}
}
return matrix.flat().filter(number => number % 2 !== 0).length;
}
console.log(oddCells(2, 3, [
[0, 1],
[1, 1]
]));
The specific input I am testing is n = 2, m = 3, indices = [[0,1],[1,1]].
I've tried to follow my code manually but I can't figure out why the two inner for loops are iterating over the nested arrays twice rather than each one once. After the first loop[ the matrix is supposed to be [[1, 2, 1], [0, 1, 0]] but instead I end up with [[1, 3, 1], [1, 3, 1]].
This is a basic problem of reusing mutable reference values.
You are repeatedly pushing the same array to the matrix, so when you modify any value in that array, you are modifying multiple areas of the matrix.
So use separate arrays:
var oddCells = function(n, m, indices) {
let matrix = [];
let k = 0;
while (k < n) {
matrix.push(Array(m).fill(0));
k++;
}
for (let i = 0; i < indices.length; i++) {
const row = indices[i][0];
const col = indices[i][1];
for (let ri = 0; ri < n; ri++) {
matrix[ri][col]++;
}
for (let ci = 0; ci < m; ci++) {
matrix[row][ci]++;
}
}
return matrix.flat().filter(number => number % 2 !== 0).length;
}
console.log(oddCells(2, 3, [
[0, 1],
[1, 1]
]));
Added maximum number according to the input length should be returned.
For example, if the length is 2 then the max among arr[0] + arr[1], arr[1] + arr[2], arr[2] + arr[3] should be returned.
Input is array and length.
I solved this in a real job interview but I think there will be a way not to use nested loop.
const add = (arr, len) => {
let rtnVal = 0
for (let i = len - 1; i < arr.length; i++) {
let temp_idx = i;
let temp_sum = 0;
for (let j = 0; j < len; j++) {
temp_sum = (temp_sum || 0) + arr[temp_idx]
temp_idx -= 1
}
if (temp_sum > rtnVal) {
rtnVal = temp_sum
}
}
return rtnVal
}
console.log(add([1, 2, 3, 4, 5, 6, 7, 8, 9], 4))
I expect the output 30
// enhanced nested loop
const add = (arr, len) => {
let rtnVal = 0;
for(let i=len-1;i<arr.length;i++){
let sum = 0
for(let j=i;j>=i-len+1;j--){
sum += arr[j]
}
if (sum > rtnVal) rtnVal = sum
}
return rtnVal
}
console.log(add([9, 9, 9, 4, 5, 6, 7, 8, 9], 3))
Use a moving window. Add up len numbers starting at the beginning. Then continue through the array adding the next number and subtracting the trailing number.
const add = (arr, len) => {
return arr.reduce((a,v,i,arr) => {
a.running += v;
if(i >= len) {
a.running -= arr[i-len];
}
if(i+1 >= len && a.largest < a.running) {
a.largest = a.running;
}
return a;
}, {
largest: Number.NEGATIVE_INFINITY,
running: 0
}).largest;
}
console.log(add([1,2,3,4,5,6,7,8,9],4)); // 30
console.log(add([-1,-1,-1,-1],2)); // -2
console.log(add([1],1)); // 1
Assuming its sorted like your example. You can use negative slice to select from end and then reduce the array.
const add = (arr, len) => arr.slice(len > arr.len ? arr.len : -len).reduce((total, num) => total + num)
console.log(add([1, 2, 3, 4, 5, 6, 7, 8, 9], 4))
My task is to split the given array into smaller arrays using JavaScript. For example [1, 2, 3, 4] should be split to [1] [1, 2] [1, 2, 3] [1, 2, 3, 4] [2] [2, 3] [2, 3, 4] [3] [3, 4] [4].
I am using this code:
let arr = [1, 2, 3, 4];
for (let i = 1; i <= arr.length; i++) {
let a = [];
for (let j = 0; j < arr.length; j++) {
a.push(arr[j]);
if (a.length === i) {
break;
}
}
console.log(a);
}
And I get the following result: [1] [1, 2] [1, 2, 3] [1, 2, 3, 4] undefined
What am I missing/doing wrong?
For the inner array, you could just start with the index of the outer array.
var array = [1, 2, 3, 4],
i, j, l = array.length,
result = [];
for (i = 0; i < l; i++) {
for (j = i; j < l; j++) {
result.push(array.slice(i, j + 1));
}
}
console.log(result.map(a => a.join(' ')));
.as-console-wrapper { max-height: 100% !important; top: 0; }
You have two issues in your code:
You need to have loop to initialize with the value of i for the inner loop so that it consider the next index for new iteration of i
You need to remove that break on the length which you have in inner loop.
let arr = [1, 2, 3, 4];
for (let i = 0; i <= arr.length; i++) {
let a = [];
for (let j = i; j < arr.length; j++) {
a.push(arr[j]);
console.log(a);
}
}
Try this
let arr = [1, 2, 3, 4];
for (let i = 0; i <= arr.length; i++) {
let a = [];
for (let j = i; j < arr.length; j++) {
a.push(arr[j]);
console.log(a);
}
}
If you don't want to mutate your array.
let arr = [1, 2, 3, 4];
let res = [];
for (let i = 0; i <= arr.length; i++) {
let a = [];
for (let j = i; j < arr.length; j++) {
a = [...a, arr[j]];
res = [...res, a];
}
}
console.log(res);
i have prepare stackblitz for this case.
let source = [1,2,3,4];
const output = [];
const arrayMultiplier = (source) => {
const eachValueArray = [];
source.forEach((item, index) => {
// Will push new array who will be sliced source array.
eachValueArray.push(source.slice(0, source.length - index));
});
//We reverse array to have right order.
return eachValueArray.reverse();
};
for(let i = 0; i <= source.length; i++) {
output.push(...arrayMultiplier(source));
source.shift(); // Will recraft source array by removing first index.
}
//Don't forget last item.
output.push(source);
console.log(output);
Is not the most shorten solution but do the job
== update after code review ==
// [...]
const arrayMultiplier = (source) => {
// Will push new array who will be sliced source array.
// We reverse array to have right order.
return source.map((item, index) => source.slice(0, source.length - index)).reverse();
};
// [...]
Use two iteration
get slice array based on loop index.
use sliced array and combine array element.
var arr = [1, 2, 3, 4];
let newArra =[];
arr.map((x,i)=> {
let remainArr = arr.slice(i);
return remainArr.forEach((y, r) => newArra.push(remainArr.slice(0, r+1)))
})
newArra.forEach(x=> console.log(x))