I am trying to create an array alternating between 2 different values with a predetermined length.
Example:
conts value1 = 1;
const value2 = 2;
cont length = 6;
//desired output
const array1 = [1, 2, 1, 2, 1, 2];
You can create the array using Array.from with the desired length and map it to have the desired values :
const value1 = 1;
const value2 = 2;
const length = 6;
const result = Array.from({ length }).map((e, ndx) => ndx % 2 ? value2 : value1);
console.log(result);
Try with:
var repeated = new Array(3).fill([1, 2]).flat();
Or more general:
function repeat(n, value){
return new Array(n).fill(value).flat();
}
result = repeat(3, [1, 2]);
Credits: https://stackoverflow.com/a/54935305/4628597
An easy beginner solution would be something like this:
function createArray(value1, value2, length){
var array = new Array()
for(var i=0; i<length;i++){
if(i%2 == 0){
array.push(value1);
}else{
array.push(value2);
}
return array;
}
}
You could take an array of values in the wanted order and use a closure over the index of the values array adjusted by taking the remainder with the length of the values array.
const values = [1, 2],
length = 6,
result = Array.from({ length }, (i => _ => values[i++ % values.length])(0));
console.log(result);
Related
I have an Array of numbers: var arr = [1,2,3,4,5]
I want to get a list like this: input_1 = 1, input_2 = input_1 * 2, input_3= input_2 * 4 ..
With me can i do in javascript?
Try
var output = {};
arr.forEach((item, i) => {
output[i+1] = i === 0 ? 1 : (output[i] * (i * 2));
});
Output
{1: 1, 2: 2, 3: 8, 4: 48, 5: 384}
You just need to keep track of the last calculated value and multiply it by the current element. There are lots of different ways to do that, here is one:
var arr = [1,2,3,4,5];
let last = 1;
const output = arr.map(el => last *= el);
console.log(output);
Here is a more functional-like implementation using the reduce method (Doc).
var arr = [1,2,3,4,5];
const result = arr.reduce(
(resultArr, _, i) => {
if (i === 0) {
// base case:
return [1];
} else {
// step case:
return [
...resultArr,
resultArr[resultArr.length - 1] * (2 ** i),
];
}
},
[],
);
console.log(result);
I want to know how can I add 3 different number to the 3n, 3n+1 and 3n+2 indices. I mean for example I have following array :
var arr = [1,1,1,2,2,2,3,3,3]
and then I want add the (3n)th to 5 and then I want add (3n+1)th of an array to 2 and (3n+2) to 3,
I mean the final array I want to be like following result array:
var result = [6,3,4,7,4,5,8,5,6]
and I try to do it as following code:
// arr = [1,1,1,2,2,2,3,3,3]
let res = [];
for (let i = 0; i < arr.length; i++) {
res.push([arr[i*3] * 5,
arr[(i*3)+1] *2,
arr[(i*3)+2] *3])
}
This should do the trick:
var arr = [1,1,1,2,2,2,3,3,3],
add = [5,2,3], res=[];
// result = [6,3,4,7,4,5,8,5,6]
for (let i=0;i<arr.length;i+=add.length) add.forEach((v,j)=>res[i+j]=arr[i+j]+v);
console.log(JSON.stringify(res))
An alternative and even shorter solution (similar to #Robin's answer) would be:
var arr = [1,1,1,2,2,2,3,3,3],
add = [5,2,3], res=[];
res=arr.map((v,i)=>v+add[i%add.length]);
console.log(JSON.stringify(res))
( I noticed #Nina came up with a very similar answer ...)
You can simply use map, making use of the fact that its function argument takes the current index an optional second argument:
var arr = [1,1,1,2,2,2,3,3,3];
var result = arr.map((num, idx) => {
switch (idx % 3) {
case 0:
return num + 5;
case 1:
return num + 2;
case 2:
return num + 3;
}
});
console.log(result);
You could mapp the array directly by taking a closure over an index for the values array for adding.
var array = [1, 1, 1, 2, 2, 2, 3, 3, 3],
add = [5, 2, 3],
result = array.map((i => v => v + add[i++ % add.length])(0));
console.log(...result);
There is an array and I want to use foreach loop to get the biggest number
Here is an array
const array2 = ['a', 3, 4, 2]
What i try in JS:
function biggestNumberInArray3(arr) {
var largest = arr[0] || null;
var number = null;
arr.forEach (value => {
number = value
largest = Math.max(largest, number);
})
return largest;
}
Looks like Math.max isn't work in here.
It returns NaN
Are there any other ways to use foreach loop to compare the elements in an array?
P.S.: this foreach loop will return 4
forEach don't return any value.
You can use Filter and Math.max
use filter to remove all non-number values.
use Math.max to get highest value.
const array2 = ['a', 3, 4, 2]
console.log(Math.max(...array2.filter(e=> !isNaN(e))))
You should use Array.reduce to find the max number and filter it before the max operation as the presence of a will cause the result to be a NaN.
const array2 = ['a', 3, 4, 2]
var max = array2.filter((num)=> !isNaN(num)).reduce((a, b)=>{
return Math.max(a, b);
});
console.log(max);
const array2 = ['a', 3, 4, 2]
var max = Math.max(...array2.filter(num => Number.isInteger(num)));
console.log(max);
If you want to use forEach , you can just add a check for numbers in your code
function biggestNumberInArray3(arr) {
var largest = null;
var number = null;
arr.forEach (value => {
if(typeof(value) === "number"){
number = value
largest = Math.max(largest, number);
}
})
return largest;
}
console.log(biggestNumberInArray3(['a', 3, 4, 2]))
Here you have another solution using only reduce():
const array2 = ['a', 3, 4, 2, "hello", {hello:"world"}];
let res = array2.reduce((max, e) => isNaN(e) ? max : Math.max(max, e), null);
console.log(res);
Remove the string from array, see demo. Not interested in efficient and simple code? forEach() only returns undefined so you'll need to get a side-effect in order to get any result. In the demo below there's a variable outside the loop that changes as the loop progresses. Eventually this variable will be the greatest number in the array.
Demo
/*
Math.max.apply()
======================================*/
const array = ['a', 3, 4, 2];
//Get rid of the string
const num = array.shift();
console.log(`Math.max.apply({}, arr) ========= ${Math.max.apply({}, array)}`);
/*
forEach()
=======================================*/
let max = 0;
array.forEach(num => {
max = num > max ? max = num : max;
});
console.log(`array.forEach() ================ ${max}`);
I have a list of numbers that is a string value using a loop I want to split this string into different variables in an array, the first of length 3 and the 6 of length 7 and the last of length 3. How can this be done using functions and loops.
We could do something like this:
let str = '000111111122222223333333444444455555556666666mmmm';
// Defines the lengths we're using
let lengths = [3,7,7,7,7,7,7,3];
let index = 0;
let result = lengths.reduce((acc,n) => {
acc.push(str.slice(index, index += n));
return acc;
} , [])
console.log(result);
You could map the sub strings.
var str = '000111111122222223333333444444455555556666666mmmm',
lengths = [3, 7, 7, 7, 7, 7, 7, 3],
result = lengths.map((i => l => str.slice(i, i += l))(0));
console.log(result);
Here's one way to do that:
let theArray = document.getElementById('theArray');
let theVariable = document.getElementById('theVariable');
let targetString = "122333444455555666666";
let dataSizes = [1, 2, 3, 4, 5, 6];
var result = [];
var pos = 0;
dataSizes.forEach( (size) => {
result.push(targetString.substr(pos, size));
pos += size;
});
theArray.textContent = result.toString();
let [one, two, three, four, five, six] = result;
theVariables.textContent = `${one}-${two}-${three}-${four}-${five}-${six}`;
a generic way of doing this will be, if you want in a variable you can use subStringLengthMaps key, :-
let str="abcdefghijklmnopqrstu";
let subStringLengthMap={a:3, b:7, c:7 , d:3};
//making pure funciton
var getStrings = function(str, subStringLengthMap){
let result =[];
Object.keys(subStringLengthMap).forEach(function(key){
let temp = str.slice(0, subStringLengthMap[key]);
result.push(temp);
str = str.replace(temp,'');
})
return result;
}
//call the function
console.log(getStrings(str, subStringLengthMap))
I have an array of numbers newArr, whose length I use to create an array filled with zeros zeroArr
const newArr = [1,3,5,8,9,3,7,13]
const zeroArr = Array.from(Array(newArr.length), () => 0);
console.log(zeroArr) // [0,0,0,0,0,0,0,0]
Now, I need to replace the last index value 0 to 10 so it should look like this:
const result = [0,0,0,0,0,0,0,10]
How to do this?
You can replace the last item in the array like this:
result[result.length-1] = 10;
Demo in Stack Snippets
const newArr = [1,3,5,8,9,3,7,13];
const zeroArr = Array.from(Array(newArr.length), () => 0);
let result = zeroArr.slice(); // To create a copy
result[result.length-1] = 10;
console.log(result);
You could use Array#map and check if the last element, then return 10 otherwise zero.
var array = [1, 3, 5, 8, 9, 3, 7, 13],
copy = array.map((_, i, a) => 10 * (i + 1 === a.length));
console.log(copy);
another option could be:
const newArr = [1,3,5,8,9,3,7,13]
const zeroArr = newArr.map(()=>0);
const arrWith10 = [...zeroArr.slice(0,-1), 10]
console.log(zeroArr) // [0,0,0,0,0,0,0,0]
console.log(arrWith10) // [0,0,0,0,0,0,0,10]
You have to copy the values in the newArr to zeroArr first then push the value 10 to the index you wanted in ZeroArr. And Print to values in 'ZeroArr'