How to get all substrings (contiguous subsequences) of my JavaScript array? - javascript

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

Related

Array Difference, nested For Loops

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

Add pattern to an array without push()

Is there a way to code this without using any methods?
a is an array, n is the number of times the pattern is repeated in the new array
const func = (a, n) => {
const arr = [];
for (let i = 0; i < n; i++) {
arr.push(...a);
}
console.log(arr);
};
func([1, 2, 3, 4], 2);
You could take a separate index and assign the values.
const func = (a, n) => {
let array = [],
i = 0;
while (n--) for (const v of a) array[i++] = v;
return array;
};
console.log(...func([1, 2, 3, 4], 2));
Well, you could use two loops and directly assign ith array item.
const func = (a, n) => {
const arr = [];
for (let i = 0; i < n; i++) {
for (let j = 0; j < a.length; j++) {
arr[i * a.length + j] = a[j]
}
}
console.log(arr);
};
func([1, 2, 3, 4], 2);
that ?
const func=(a, n)=>
{
const arr = []
let p = 0
for (let i=0;i<n;++i) for(let v of a) arr[p++] = v
console.log(JSON.stringify(arr));
}
func([1, 2, 3, 4], 2);
You could use the spread operator to create a new array for each iteration of the loop. This would mean that your arr variable can't be a constant though since it gets overwritten with a new array.
const func = (a, n) => {
let arr = [];
for (let i = 0; i < n; i++) {
arr = [...arr, ...a];
}
console.log(arr);
};
func([1, 2, 3, 4], 2);

Iterate over shallow copy of nested array in Javascript

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

Group items in for loops

Using JavaScript, I am looping through an array of values.
var values = [1, 2, 1, 3, 1, 3, 4, 1]
for (let i = 0; i < values.length; i++) {
console.log(values[i])
}
I want to get the sum for each group of 4. I could do this in multiple for loops by using:
var values = [1, 2, 1, 3]
var sum1 = 0
for (let i = 0; i < values.length; i++) {
sum1 += parseInt(values[i]);
}
var values = [1, 3, 4, 1]
var sum2 = 0
for (let i = 0; i < values.length; i++) {
sum2 += parseInt(values[i]);
}
How can I group by 4 and get the sum of the values for each group by using one for loop?
Can slice() the array and reduce() each sub array
var values = [1, 2, 1, 3, 1, 3, 4, 1]
var sums =[];
for(let i=0; i< values.length; i=i+4){
const subArr= values.slice(i,i+4);
const sum = subArr.reduce((a,c)=>a+c)
sums.push(sum)
}
console.log(sums)
You can use a counter. Reset the counter and sum variable when it reaches the group limit, like below example :
var values = [1, 2, 1, 3, 1, 3, 4, 1];
var result = [];
var counter = 0;
var sum = 0;
for(var i = 0; i < values.length; i++){
counter++;
sum += values[i];
if(counter === 4 || i === values.length-1){
result.push(sum);
counter = 0;
sum = 0;
}
}
console.log(result);
You could take an array as result set and divide the index by 4 and take the integer value for adding the value.
var values = [1, 2, 1, 3, 1, 3, 4, 1],
grouped = values.reduce((r, v, i) => {
var k = Math.floor(i / 4);
r[k] = r[k] || 0;
r[k] += v;
return r;
}, []);
console.log(grouped);

How do I sum up 2 dimensional array, ex index 0+index0

I encountered a problem!
for example! here is my 2 dimensional array: var array=[[1,2,3,4],[2,3,4,5],[3,4,5,6]];
and my desired outcome is : [[1,2,3,4],[2,3,4,5],[3,4,5,6],[6,9,12,15]]
the [6,9,12,15] came from adding the same index numbers of the previous inner arrays. (ex 1+2+3, 2+3+4, 3+4+5, 4+5+6 more clear : index 1 + index 1+ index1 produces 9)
I am so confused so far, the closes i did was to sum up [1,2,3,4][2,3,4,5][3,4,5,6], but I cant seem to do something with each and individual numbers :(
The question requested me to do nested for loops, So i cant use any thing like reduce, map, flatten, etc...
try with this way:https://jsfiddle.net/0L0h7cat/
var array=[[1,2,3,4],[2,3,4,5],[3,4,5,6]];
var array4 = [];
for (j = 0; j < array[0].length; j++) {
var num =0;
for(i=0;i< array.length;i++){
num += array[i][j];
}
array4.push(num);
}
array.push(array4);
alert(array);
Just iterate over the outer array and the inner arrays and add the values to the result array array[3].
var array = [[1, 2, 3, 4], [2, 3, 4, 5], [3, 4, 5, 6]];
array.forEach(function (a) {
a.forEach(function (b, i) {
array[3] = array[3] || [];
array[3][i] = (array[3][i] || 0) + b;
});
});
document.write('<pre>' + JSON.stringify(array, 0, 4) + '</pre>');
https://jsfiddle.net/0L0h7cat/
var array = [
[1, 2, 3, 4],
[2, 3, 4, 5],
[3, 4, 5, 6]
];
var sumArr = [];
for (var i = 0; i < array[0].length; i++) {
sumArr[i] = 0;
for (var j = 0; j < array.length; j++)
sumArr[i] += array[j][i];
}
array.push(sumArr);
If you are interested in Arrow Functions, this will work:-
var array = [[1, 2, 3, 4],[2, 3, 4, 5],[3, 4, 5, 6]];
var count = [];
array.forEach(x => x.forEach((y, i) => count[i] = (count[i] || 0) + y));
array.push(count);
console.log(array);
NOTE: Not cross browser support yet.
This is how -
var array=[[1,2,3,4],[2,3,4,5],[3,4,5,6]];
var array2=[]
for (var i = array[0].length;i--;) {
var sum=0;
for (var j = array.length; j--;) {
sum=sum+array[j][i];
}
array2.push(sum)
}
array.push(array2.reverse());
document.write('<pre>'+JSON.stringify(array) + '</pre>');
But I'm sure there are more elegant methods. I'm just learning by answering questions myself.
A simplistic approach with just conventional for loops
var input = [[1,2,3,4],[2,3,4,5],[3,4,5,6]];
function getSumOfArrayOfArrays(inputArray) {
var length = inputArray.length;
var result = [];
for(var i=0; i<length; i++){
for(var j=0; j<=3; j++){
result[j] = result[j] ? result[j] + inputArray[i][j] : inputArray[i][j];
}
}
return result;
}
var output = getSumOfArrayOfArrays(input); // [6,9,12,15]
var desiredOutput = input;
desiredOutput.push(output)
document.write(JSON.stringify(desiredOutput));
// [[1,2,3,4],[2,3,4,5],[3,4,5,6],[6,9,12,15]]
I try to avoid writing nested for loops.
var arrayOfArrays=[
[1,2,3,4],
[2,3,4,5],
[3,4,5,6]
];
//define a function to extend the Array prototype
Array.prototype.add = function(otherArray){
var result = [];
for(var i = 0; i < this.length; i++) {
result.push( this[i] + otherArray[i] )
}
return result;
};
//reduce array of arrays to get the result array `sum`
var sum = arrayOfArrays.reduce(function(arrayA, arrayB){
//`arrayA`+`arrayB` becomes another `arrayA`
return arrayA.add(arrayB)
});
//put `sum` back to `arrayOfArrays`
arrayOfArrays.push(sum);
document.write('<pre>' + JSON.stringify(arrayOfArrays) + '</pre>');

Categories

Resources