How to add item in array every x items? - javascript

How can I add an item every x item in an array?
For example I would like to add an item every 10 items in the 3rd position:
const arr = [1,2];
const result = [1,2, item];
or
const arr = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16];
const result = [1,2,item,3,4,5,6,7,8,9,10,11,item,12,13,14,15,16];

You could take a while loop and check the length after taking the starting position and the interval length as increment value.
var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16],
pos = 2;
interval = 10;
while (pos < array.length) {
array.splice(pos, 0, 'item');
pos += interval;
}
console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Here's an option that doesn't alter the original array.. just loop and insert to a new array.
/**
* Add an item to an array at a certain frequency starting at a given index
* #param array arr - the starting array
* #param mixed item - the item to be inserted into the array
* #param integer starting = the index at which to begin inserting
* #param integer frequency - The frequency at which to add the item
*/
function addItemEvery(arr, item, starting, frequency) {
for (var i = 0, a = []; i < arr.length; i++) {
a.push(arr[i]);
if ((i + 1 + starting) % frequency === 0) {
a.push(item);
i++;
if(arr[i]) a.push(arr[i]);
}
}
return a;
}
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16];
arr = addItemEvery(arr, "item", 2, 3);
console.log(arr);

Use arr.splice method. Calculate index for every tenth element like 2,12,22...
var arr = [];
arr[0] = 1;
arr[1] = 2;
arr[2] = 3;
arr[3] = 4;
arr[4] = 5;
console.log(arr.join());
arr.splice(2, 0, "Lene");
console.log(arr.join());
For more reference
How to insert an item into an array at a specific index?

Related

Get a value from one array and add to remaining elements of both Array in JS

Let's say I have the following 2 Arrays:
let a = [5,5,5,5,0]
let b = [5,5,5,5,0]
Assuming that both arrays has the same length:
I want to get a value from an element of one Array and add the +1 itself and to other remaining elements. If the the picked value is still bigger than zero, then it should also continue adding it to elements of other array from starting index.
Example_1: If I pick a[2] then the outcome should be:
a = [5,5,1,6,1] // a[2] became 0 after picking 5, then in each remaining element we add +1 and continue to next array.
b = [6,6,5,5,0]
Example_2: Or If I pick b[3] from initial arrays, then the outcome should be:
a = [6,6,6,5,0] // b[3] became 0 after picking 5, then in each remaining element we add +1 and move to next array until our value becomes zero
b = [5,5,5,1,1]
Here is my attempt:
let pickedValue = a[2]
for (let index = 2; index < a.length; index++) {
if (pickedValue > 0) {
a[index] += 1
pickedValue--
}
}
for (let index = 0; index < pickedValue; index++) {
if (pickedValue > 0) {
b[index] += 1
pickedValue--
}
}
Can we do this in more dynamic way with maybe one loop?
You just need to iterate through both arrays. The chosen array should be iterated from the target + 1 up to its lenght, and the other array, from 0 up the target.
You can see that I directly put a 1 to the chosen array at index target, instead of put a 0 and add +1.
(Also use some regex in order to catch the number between the brackets, from this SO answer)
let a = [5,5,5,5,0]
let b = [5,5,5,5,0]
const ans = prompt("Pick an element (e.g `a[2]` or `b[3]`)");
const [chosenArray, otherArray] = ans[0] === 'a' ? [a, b] : [b, a];
const target = parseInt(ans.match(/(?<=\[).+?(?=\])/), 10);
chosenArray[target] = 1;
for (let i = target + 1; i < chosenArray.length; ++i)
++chosenArray[i];
for (let i = 0; i < target; ++i)
++otherArray[i];
console.log(a, b)
You could tkae an object with same named properties of arrays and hand over target key and index and then update until no more value is to disperse.
const
update = (source, target, index) => {
const keys = Object.keys(source);
let value = source[target][index];
source[target][index] = 0;
while (value--) {
source[target][index++]++;
if (index === source[target].length) {
index = 0;
target = keys[(keys.indexOf(target) + 1) % keys.length];
}
}
return source;
};
console.log(update({ a: [5, 5, 5, 5, 0], b: [5, 5, 5, 5, 0] }, 'a', 2));
console.log(update({ a: [5, 5, 5, 5, 0], b: [5, 5, 5, 5, 0] }, 'b', 3));
.as-console-wrapper { max-height: 100% !important; top: 0; }

How to filter an array of numbers and take certain intervals?

I have this type of array.
[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24]
Requirements to filter the array are
Omit every 4 items
Take the following 4 items
And continue until the end of the array.
At the end It should return [5,6,7,8,13,14,15,16,21,22,23,24]
const values = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24];
newValues = values.filter((v, i) => i % 8 > 3)
console.log(newValues)
You could slice the chunks and add to the result array.
const
data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24],
result = [];
let i = 0;
while (i < data.length) result.push(...data.slice(i += 4, i += 4));
console.log(...result);
You can create a partitioning function for achieving your result.
const arr = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24];
/**
* Pertition the array and create a new array.
*
* #param {array} arr The array to pertition.
* #param {number} skip The number of elements to skip
* #param {number} take Take the number of elements need to take after skipping.
*
* #return {array} The resulting array after pertition.
*/
const arrayAfterPertition = (arr, skip, take) => {
const length = arr.length;
let ans = [];
/** If there are not enough elements to skip then returns empty array */
if (length <= skip) return [];
let takeIndex = skip;
while (takeIndex < length) {
ans = [...ans, ...arr.slice(takeIndex, takeIndex + take)];
takeIndex = takeIndex + take + skip;
}
return ans;
}
console.log(JSON.stringify(arrayAfterPertition(arr, 4, 4)));
.as-console-wrapper {min-height: 100%!important; top: 0}
Lodash if you don't mind. Using Loash#chunk
const nums = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24];
const chunkSize = 4;
const result = _.chunk(nums, chunkSize)
.filter((v,i) => i % 2 ===1)
.flat();
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
<script src="https://cdn.jsdelivr.net/lodash/4.10.0/lodash.js"></script>

How to select numbers in array

I'm trying to select every second element in the group of three. e.g.
[4, 5, 3, 2, 3, 1, 4, 5, 3]
Result: 5, 3, 5
How can I achieve this?
You can use Array.prototype.filter and modulo operation:
const result = [4, 5, 3, 2, 3, 1, 4, 5, 3].filter((item, i) => (i+2) % 3 === 0);
console.log(result)
var arr = [4, 5, 3, 2, 3, 1, 4, 5, 3],
filtered = arr.filter((val,idx) => idx % 3 == 1);
You have to split the array in chunks, then take the second element of every chunk:
/**
* Returns an array with arrays of the given size.
*
* #param myArray {Array} array to split
* #param chunk_size {Integer} Size of every group
*/
function chunkArray(myArray, chunk_size){
var index = 0;
var arrayLength = myArray.length;
var tempArray = [];
for (index = 0; index < arrayLength; index += chunk_size) {
myChunk = myArray.slice(index, index+chunk_size);
// Do something if you want with the group
tempArray.push(myChunk);
}
return tempArray;
}
// Split in group of 3 items
function getResult () {
// Outputs : [ [1,2,3] , [4,5,6] ,[7,8] ]
var chunked = chunkArray([1,2,3,4,5,6,7,8], 3);
var result = [];
for(var i = 0; i < chunked.length; i++){
result.push(chunked[i][1]);
}
return result;
}
console.log(getResult());
Chunking ref: https://ourcodeworld.com/articles/read/278/how-to-split-an-array-into-chunks-of-the-same-size-easily-in-javascript
//this function splits arrays into groups of n
function chunk(arr, limit) {
var chunks = [];
for (var i=0,len=arr.length; i<len; i+=limit)
chunks.push(arr.slice(i,i+limit));
return chunks;
}
var arr = [4, 5, 3, 2, 3, 1, 4, 5, 3]
//split array in groups
var chunked = chunk(arr, 3);
//for each array in chunked array, do something with second item
chunked.forEach(function(i) {
console.log(i[1]);
});
//You can also do:
chunked[2][1]

Sorting an array by chunks of 3

Assume that you have an array and want to divide it by chunks of 3. If the array is..
let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13];
...the new array would be
let newArr = [1, 4, 7, 10, 13, 2, 5, 8, 11, 3, 6, 9, 12]
// In other words:
1 2 3
4 5 6
7 8 9
10 11 12
13
The chunking part should be this code (if sorted like newArr):
let chunkedArr = _.chunk(_.toArray(newArr), 3);
...however I couldn't figure out how to sort the arr to newArr to be able to chunk in the right order. What is the proper way of handling such case?
Please note that the integers are just pseudo and I will use proper objects of array.
One option is to use ES6 reduce to group the array into a multidimensional array. Use concat to flatten the multidimensional array.
[].concat(...) - basically flattens the multidimensional array. Starting with an empty array [], you concat each secondary array. Use the spread operator (...) to reiterate each secondary array and concat each.
let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13];
let groups = 3;
let newArr = [].concat(...arr.reduce((c, v, i) => {
let k = i % groups;
c[k] = c[k] || [];
c[k].push(v);
return c;
}, []));
console.log(newArr);
Please try the following (jsfiddle):
//This version works for variable chunk sizes as well.
let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13];
alert(chunks(arr, 3)); //You can update chunk size here
function chunks(arr, chunkSize) {
var result = [];
var index = 0;
for (var i = 0; i < chunkSize; i++) {
for (var j = 0; j < arr.length / chunkSize; j++) {
if (arr[i + (chunkSize * j)] != null)
result[index++] = arr[i + (chunkSize * j)];
}
}
return result;
}
//This version only works for chunks of size 3.
let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13];
let subArr1 = [];
let subArr2 = [];
let subArr3 = [];
var result = [];
var i = 0, j = 0, k = 0;
for (var index = 0; index < arr.length; index++) {
if (index % 3 == 0) {
subArr1[i++] = arr[index];
}
if (index % 3 == 1) {
subArr2[j++] = arr[index];
}
if (index % 3 == 2) {
subArr3[k++] = arr[index];
}
}
result.push(subArr1, subArr2, subArr3);
alert(result);
Please check this it may help you. I also take a reference from here. Please check and let us know. any thing else you need.
Thanks
Here is the sample code.
var i,j,resArr,chunkSize = 10;
for (i=0,j=array.length; i<j; i+=chunk) {
resArr = array.slice(i,i+chunk);
}
const original = [1,2,3,4,5,6,7,8,9,10,11,12,13]
const chunks = 3
function getChunckedArr(arr, n) {
let sub = new Array(n);
let result = [];
for (let i=0; i<sub.length; i++)
sub[i] = []
arr.forEach(function (val, index){
let o = (index % n);
sub[o][sub[o].length] = val;
});
for (let i=0; i<sub.length; i++)
result.push.apply(result, sub[i]);
return result;
}
const chunked = getChunckedArr(original, chunks);

Adding an element to an array from inside a for loop

in the for loop below I have arr[i] = x * i; I am basically trying to get multiples of numbers. the results of the code I have now is [0, 2, 4, 6, 8, 10, 12, 14, 16, 18] I do not want the first element of the array to be 0 ..
var n = 10;
var arr = [];
var x = 2;
for(var i = 0; i < n; i++ ){
//arr[0] = x;
arr[i] = x * i;
// arr.push(x += x)
}
console.log(arr)
i want to be able to do arr[0] and see x. In this case that would be 2 (the number for the multiples..I don't know math words) [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
I know that the problem is that 2 * 0 is equal to 0 so arr[0] = 0. what is the best way to make it so that the first element will be the second loop. I was thinking about making an if statement. or using an array method that slices of the beginning of the array. I hope there is an easier way like changing the for loop.
There are two simple ways to fix this
Change the loop starting value
var arr = [],
x = 2,
n = 10;
for (var i = 1; i <= n; i++) { // Start with `1`
arr.push(x * i);
}
Or, multiply with the next value of i,
var arr = [],
x = 2,
n = 10;
for (var i = 0; i < n; i++) {
arr.push(x * (i + 1)); // Multiply with i + 1
}
If you still want to solve it with array index assignment, then just remove the first element, with Array.prototype.slice after creating the entire array, like this
var n = 10,
arr = [],
x = 2;
for (var i = 0; i <= n; i++) { // Note the limits, 0 to <= n
arr[i] = x * i;
}
console.log(arr);
// [ 0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20 ]
arr = arr.slice(1);
console.log(arr);
// [ 2, 4, 6, 8, 10, 12, 14, 16, 18, 20 ]

Categories

Resources