Start a for loop on specific index and loop for array length - javascript

I'm trying to do a for loop on an array and be able to start that loop on a specific index and loop over the array x amount of times.
const array = ['c','d','e','f','g','a','b','c']
I want to loop 8 indexes starting at any index I wish. Example starting at array[4] (g) would return
'g','a','b','c','c','d','e','f'
This is what I've tried so far
const notes = ['c','d','e','f','g','a','b','c']
var res = []
for (var i = 4; i < notes.length; i++) {
res.push(notes[i])
}
console.log(res)

You can use modulo % operator.
const getArray = (array, index) => {
const result = [];
const length = array.length;
for (let i = 0; i < length; i++) {
result.push(array[(index + i) % length]);
}
return result;
};

Simple way.
var notes = ['c','d','e','f','g','a','b','c'];
function looparr(arr, start)
{
var res = [], start = start || 0;
for(var index = start, length=arr.length; index<length; index++)
{
res.push(arr[index]);
index == (arr.length-1) && (index=-1,length=start);
}
return res;
}
console.log(looparr(['c','d','e','f','g','a','b','c'], 0));
console.log(looparr(['c','d','e','f','g','a','b','c'], 2));
console.log(looparr(['c','d','e','f','g','a','b','c'], 4));
console.log(looparr(['c','d','e','f','g','a','b','c']));

Very simple solution below :)
While i < index, remove the first character from the array, store it in a variable and then add it back onto the end of the array.
let array = ['c','d','e','f','g','a','b','c'];
var index = 4;
for(var i = 0; i < index; i++) {
var letter1 = array.shift(i); // Remove from the start of the array
array.push(letter1); // Add the value to the end of the array
}
console.log(array);
Enjoy :)

Related

How find the array index for two array comparision and return once array item less than another?

I would like to compare two array then return the index once first array less than second array. But if the start value of first array greater than the second array, must skip until first array value less than second array. For example
case1: This must return index = 2 (exampleArr1 < exampleArr2 at index =2)
var exampleArr1 = [15,9,7,5,3,1];
var exampleArr2 = [2,6,8,12,17,22];
function compareArray(exampleArr1,exampleArr2){
...
return result
}
case2: This must return index = 6 (exampleArr1 < exampleArr2 at index =6)
var exampleArr1 = [1,2,4,5,15,9,7,5,3];
var exampleArr2 = [2,3,5,6,2,6,8,12,17];
function compareArray(exampleArr1,exampleArr2){
...
return result
}
Any advice or guidance on this would be greatly appreciated, Thanks.
A simple for loop will suffice. In our loop, we already have the index so we just compare the first array at this index with the second array at this index.
const compareArray = (arr1, arr2) => {
let startIndex = 0
if (arr1[0] < arr2[0]) {
// find the index from arr1 that is greater than arr2
startIndex = arr1.findIndex((a, index) => a > arr2[index])
}
for (let i = startIndex; i < arr1.length; i++) {
if (arr1[i] < arr2[i]) {
return i
}
}
}
const exampleArr1 = [15,9,7,5,3,1]
const exampleArr2 = [2,6,8,12,17,22]
const exampleArr3 = [1,2,4,5,15,9,7,5,3]
const exampleArr4 = [2,3,5,6,2,6,8,12,17]
console.log(compareArray(exampleArr1, exampleArr2))
console.log(compareArray(exampleArr3, exampleArr4))
Please use the findIndex method in your function like
var exampleArr1 = [15,9,7,5,3,1];
var exampleArr2 = [2,6,8,12,17,22];
function compareArray(exampleArr1,exampleArr2) {
if (exampleArr1[0] < exampleArr2[0]) {
exampleArr1 = exampleArr1.slice(1);
}
return exampleArr1.findIndex(function(e, i) { return exampleArr2[i] > e; });
}
console.log(compareArray(exampleArr1, exampleArr2));

How to split an array into even length chunks? [duplicate]

This question already has answers here:
Splitting a JS array into N arrays
(23 answers)
Closed 3 years ago.
I want to split an array in even (or as even as possible) chunks.
The input of the function should be the array and the size of the chunks.
Say you have the array
[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17]
If you put it in the function below, with 5 as chunk size, it will result in the following
[[1,2,3,4,5],[6,7,8,9,10],[11,12,13,14,15],[16,17]
However, I want the result to be
[[1,2,3,4,5],[6,7,8,9],[10,11,12,13],[14,15,16,17]
Which means sacrificing the length of the arrays before to make them only differ one in length.
The function I'm currently using is stated below. I've tried various things with modulo but I can't figure it out.
function chunkArray(myArray, chunkSize){
var arrayLength = myArray.length;
var tempArray = [];
for (index = 0; index < arrayLength; index += chunkSize) {
myChunk = myArray.slice(index, index+chunkSize);
// Do something if you want with the group
tempArray.push(myChunk);
}
return tempArray;
}
With this solution you get evenly split array items until the last item which incorporates any left over items (collection of items that's length is less than the chunk size.)
const a = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17]
const chunk = 4
const chunk_array = (a, c) => {
let arr = []
a.forEach((_, i) => {
if (i%chunk === 0) arr.push(a.slice(i, i+chunk))
})
const [left_overs] = arr.filter(a => a.length < chunk)
arr = arr.filter(a => a.length >= chunk)
arr[arr.length-1] = [...arr[arr.length-1], ...left_overs]
return arr
}
console.log(
chunk_array(a, chunk)
)
My solution!
const chunk = (arr, chunkSize) => {
let chunked = [];
for (let i = 0; i< arr.length; i+=chunkSize){
chunked.push(
arr.slice(i, (i + chunkSize))
);
}
return chunked;
};
const data = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17];
console.log(chunk(data, 5));
// returns [[1,2,3,4,5],[6,7,8,9,10],[11,12,13,14,15],[16,17]]
You could check with a modulo if your array length is odd :
let MY_CHUNK_CONST = 5
let first_chunk_size = MY_CHUNK_CONST,
other_chunk_size = MY_CHUNK_CONST;
let myArray = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17];
modulo_res = myArray.length % 2; // 0 if even 1 if odd
if(modulo_res){
other_chunk_size = first_chunk_size - 1;
}
var tempArray = [];
myChunk = myArray.slice(0, 0+first_chunk_size);
tempArray.push(myChunk);
for (index = 1; index < myArray.length; index += other_chunk_size) {
myChunk = myArray.slice(index, index+other_chunk_size);
// Do something if you want with the group
tempArray.push(myChunk);
}
console.log(tempArray)
// [[1,2,3,4,5],[6,7,8,9],[10,11,12,13],[14,15,16,17]
Hope it helps.

How to get even numbers array to print first instead of odds?

So I have this function where I've need to take out the evens and odds and put them into separate arrays but I need the evens array to print first rather than the odds.
var numbersArray = [1,2,34,54,55,34,32,11,19,17,54,66,13];
function divider(numbersArray) {
var evensOdds = [[], []];
for (var i = 0; i < numbersArray.length; i++) {
evensOdds[i & 1].push(numbersArray[i]);
}
return evensOdds;
}
If you want to split the number by their even and odd values, instead of using the index (i), determine the sub array to push into using the value - numbersArray[i] % 2.
var numbersArray = [1,2,34,54,55,34,32,11,19,17,54,66,13];
function divider(numbersArray) {
var evensOdds = [[], []];
for (var i = 0; i < numbersArray.length; i++) {
evensOdds[numbersArray[i] % 2].push(numbersArray[i]);
}
return evensOdds;
}
console.log(divider(numbersArray));
If you want to split them by even and odd indexes use (i + 1) % 2 to determine the sub array to push into:
var numbersArray = [1,2,34,54,55,34,32,11,19,17,54,66,13];
function divider(numbersArray) {
var evensOdds = [[], []];
for (var i = 0; i < numbersArray.length; i++) {
evensOdds[(i + 1) % 2].push(numbersArray[i]);
}
return evensOdds;
}
console.log(divider(numbersArray));
Just for fun, a forEach version of the accepted answer.
var numbersArray = [1,2,34,54,55,34,32,11,19,17,54,66,13];
var even_odd = [ [], [] ];
numbersArray.forEach( e => even_odd[e%2].push(e) );
console.log(even_odd);

Group items of two in one array

I am trying to push numbers in an array into another array in groups of two.
If I have an array [1,4,3,2]; it should return [[1,4],[3,2]];
var arrayPairSum = function(nums) {
var len = nums.length / 2;
var arr = [];
for(var i = 0; i < len; i ++) {
var newArr = [];
newArr.push(nums[i]);
newArr.push(nums[i + 1]);
arr.push(newArr);
}
console.log(arr); //this should give me [[1,4],[3,2]];
};
arrayPairSum([1,4,3,2]);
can anyone see what I need to do to achieve this? I cannot figure it out.
You can use reduce method to achieve this. reduce method accepts a callback method provided on every item in the array.
In the other words, this method applies a function against an accumulator and each element in the array (from left to right) to reduce it to a single value.
var array=[1,4,3,2,8];
var contor=array.reduce(function(contor,item,i){
if(i%2==0)
contor.push([array[i],array[i+1]].filter(Boolean));
return contor;
},[]);
console.log(contor);
If you really want to iterate over the array, may skip every second index, so i+=2 ( as satpal already pointed out) :
var arrayPairSum = function(nums) {
var len = nums.length - 1;//if nums.length is not even, it would crash as youre doing nums[i+1], so thats why -1
var arr = [];
for (var i = 0; i < len; i += 2) {
var newArr = [];
newArr.push(nums[i]);
newArr.push(nums[i + 1]);
arr.push(newArr);
}
console.log(arr); //this should give me [[1,4],[3,2]];
};
arrayPairSum([1, 4, 3, 2]);
The upper one crops away every non pair at the end. If you want a single [value] at the end, may go with
len=nums.length
And check later before pushing
if(i+1<nums.length) newArr.push(nums[i+1]);
You were pretty close. Simply change the length to nums.length and in the loop increment i by 2.
var arrayPairSum = function(nums) {
var len = nums.length - 1;
var arr = [];
for(var i = 0; i < len; i+=2) {
var newArr = [];
newArr.push(nums[i]);
newArr.push(nums[i + 1]);
arr.push(newArr);
}
console.log(arr); //this should give me [[1,4],[3,2]];
};
arrayPairSum([1,4,3,2]);

Slice an array to multiple parts [duplicate]

This question already has answers here:
Split array into chunks
(73 answers)
Closed 6 years ago.
My example:
let arr = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18];
let slice = (source, index) => source.slice(index, index + 4);
let length = arr.length;
let index = 0;
let result = [];
while (index < length) {
let temp = slice(arr, index);
result.push(temp);
index += 4;
}
console.log(result);
Logging:
[[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16],[17,18]]
I want to slice the array to multiple parts for per 4 items [1,2,3,4] [5,6,7,8]...
The code is working fine.
I have 2 questions:
1/. Is there another way to do that via using inline code? Ex: result = arr.slice(...)
2/. After I define:
let push = result.push;
why cannot I still use:
push(temp)
Error message:
Uncaught TypeError: Array.prototype.push called on null or undefined
UPDATE: I've updated the solution based on the answers. Hope it's helpful.
let arr = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18];
let result = [];
arr.forEach((x,y,z) => !(y % 4) ? result.push(z.slice(y, y + 4)) : '');
console.log(result);
Logging:
[[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16],[17,18]]
A simple way to do it
var chunckArray = function(array, chunkCount){
var chunks = [];
while(array.length){
chunks.push(array.splice(0, chunkCount);
}
return chunks;
}
A non consumative way :
var chunckArray = function(array, chunkCount){
var chunks = [], i, j;
for (i = 0, j = array.length; i<j; i+= chunkCount) {
chunks.push(array.slice(i, i + chunkCount);
}
return chunks;
}
You can also do it using a for loop which will give you a same result:
let arr = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18];
console.log(arr.length);
var result=[];
for(var i = 0; i < arr.length; i+=4) {
result=arr.slice(i, i+4);
console.log(result);
}
I've done this using a simple reduce (see plnkr):
let arr = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18];
var counter = -1;
var result = arr.reduce((final, curr, i) => {
if (i % 4 === 0) {
final.push([curr])
counter++;
} else {
final[counter].push(curr);
}
return final;
}, []);
console.log(result);
You can tweak the 4 and substitute it with a variable chuckSize this will allow you to be able reapply to other things - you could also wrap this in a function with paramerters (array, chunkSize) if you wanted to

Categories