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'
Related
I know this is a very basic question, but I am not able to write the correct code for this. Let's say I have 3 arrays:
arr1 = [1,2,3,4]
arr2 = [5,6,7,8]
arr3 = [7,3,2,1]
I want the sum of the last index, i.e. 4+ 8 + 1 = 13
I am not able to write the correct for loop for the same.
EDIT :
My array is inside an object as shown below:
So, I will have more arrays inside the object. So how do I proceed with this?
let ree = {
arr1: [1, 2, 3, 4],
arr2: [5, 6, 7, 8],
arr3: [7, 3, 2, 1]
};
let total = 0;
for (var key in ree) {
if (Array.isArray(ree[key])) {
total += ree[key][ree[key].length - 1];
}
}
console.log(total);
try this short and easy solution
let arr1 = [1,2,3,4]
let arr2 = [5,6,7,8]
let arr3 = [7,3,2,1]
arrList = [arr1,arr2,arr3]
finalSum = arrList.reduce((acc, cur) => acc+[...cur].pop(), 0)
i created a copy of arrays in reduce as pop modifies original array.
if your array is inside object as key value pair you can get it as array like this
let yourObject = {1:arr1, 2:arr2, 3:arr3}
let arrList = Object.values(yourObject);
an array assigned to a key in an object can be accessed like this
let yourObject = {'somekey':[1,2,3]};
arrList = yourObject.somekey;
console.log(arrList);
You can do something like this using array.length property,
sum = arr1[arr1.length - 1] + arr2[arr2.length - 1] + arr3[arr3.length - 1];
If they are inside another array you can do something like this,
let parentArr = [[1,2,3,4],[5,6,7,8],[7,3,2,1]];
let sum = 0;
for(let i =0;i<parentArr.length; i++) {
sum = sum + parentArr[i][parentArr[i].length - 1];
}
console.log(sum);
If the arrays are inside an object you can do the following,
let parentObj = {'arr1': [1,2,3,4], 'arr2': [5,6,7,8], 'arr3': [7,3,2,1]};
let sum = 0;
let keys = Object.keys(parentObj);
for(let i =0;i<keys.length; i++) {
sum = sum + parentObj[keys[i]][parentObj[keys[i]].length - 1];
}
console.log(sum);
Basic thing to know before we continue :
how many arrays you have ?
can array be empty ?
if number of arrays is static i.e. 3 and they can't be empty then use sabir.alam's
else please define your requirements.
Shorter answer:
const parentArr = [[1,2,3,4],[5,6,7,8],[7,3,2,1]];
const answer = parentArr.map(e=>e[e.length-1]).reduce((x,y)=>x+y);
console.log(answer);
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);
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);
I have an array of values. I want to make a second array based on the first one with stricter criteria. For example, what I want specifically is:
arrayOne[1,1,1,1,1,2,2,2,3,3,3,3,4,4,4,4,4,5,5,5]
How would I make it so in my new array, only the values that show up 5 times are a part of the array and only show up once. Example: arrayTwo [1,4]
I'm fairly new to JavaScript and have been given an opportunity to code a decision making system for one of my business courses instead of doing the final exam. Any help you can give would be much appreciated. Thank You.
You could use a hash table, which counts each found element and then use the count for filtering and get only the fifth element as result set in a single loop.
var array = [1, 1, 1, 1, 1, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 5, 5, 5],
count = Object.create(null),
result = array.filter(v => (count[v] = (count[v] || 0) + 1) === 5);
console.log(result);
I commented the code with the steps I took:
const arrayOne = [1, 1, 1, 1, 1, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 5, 5, 5];
function method(arr, minimum) {
//Create an object containing the amount each number occurs
const occurrences = arr.reduce((o, n) => {
//If number is already in the object add 1
if (o[n]) o[n] = o[n] + 1;
//Else set its occurence to 1
else o[n] = 1;
//Return the object for the next iteration
return o;
}, {});
//Deduplicate the array be creating a Set(every elements can only occur once) and spread it back into an array
const deduplicate = [...new Set(arr)];
//Filter array to only contain elements which have the minimum of occurences
const filtered = deduplicate.filter(n => occurrences[n] >= minimum);
return filtered;
}
console.log(method(arrayOne, 5));
You can use a Map for this.
let arrayOne = [1, 1, 1, 1, 1, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 5, 5, 5];
let counterMap = new Map();
arrayOne.forEach(value => {
let valueStr = value.toString();
counterMap.set(valueStr, counterMap.has(valueStr) ? counterMap.get(valueStr) + 1 : 1);
});
let arrayTwo = [];
counterMap.forEach((value, key, map) => {
if(value >= 5) {
arrayTwo.push(key);
}
});
console.log(arrayTwo);
Not the most elegant answer, but I assume you're looking just to find all values that appear at least 5 times.
const arrayOne = [1,1,1,1,1,2,2,2,3,3,3,3,4,4,4,4,4,5,5,5]
const arrayTwo = Object.entries(arrayOne.reduce((obj, num) => {
if(!obj[num]){
obj[num] = 1
} else {
obj[num] = obj[num] + 1
}
return obj
}, {})).filter(([key, value]) => {
return value >= 5
}).map((item) => {
return parseInt(item[0])
})
console.log(arrayTwo)
const a = [1,1,1,1,1,2,2,2,3,3,3,3,4,4,4,4,4,5,5,5,5,5,5,5,5,5];
Define a function that will take an array and numOfOccurrences
const filterByOcur = (arr, numOfOccurrences) => {
// create an object to act as a counter this will let us
// iterate over the array only once
const counter = {};
const res = new Set();
for (let num of arr) {
// if it's the first time we see the num set counter.num to 1;
if (!counter[num]) counter[num] = 1;
// if counter.num is greater or equal to numOfOccurrences
// and we don't have the num in the set add it to the set
else if (++counter[num] >= numOfOccurrences && !res.has(num)) res.add(num);
}
// spread the Set into an array
return [...res];
};
console.log(
filterByOcur(a, 5)
);
There is number of ways of doing this, I will try to explain this step by step:
Array declaration
const a = [1,1,1,1,1,2,2,2,3,3,3,3,4,4,4,4,4,5,5,5]
Method to count elements in an array, we are using reducer function that as a first argument takes object where key is our value from array and has a incremental number as a value. Remeber to start reducer with empty object
const counted = a.reduce((counter, value) => {
if (counter[value]) counter[value]++
else counter[value] = 1
return counter
}, {})
Make your array unique with Set constructor
const uniq = Array.from(new Set(a))
Fire filter functions on the uniq array with a help of counted array, look how we access it:
const onlyOne = uniq.filter(val => counted[val] === 1)
const onlyFive = uniq.filter(val => counted[val] === 5)
Merge all filtered arrays into one
const final = [].concat(onlyOne, onlyFive)
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))