Related
I would like to iterate over the array and getting an average from 5 next elements, not from the whole array. I try to do it by code bellow, but it doesn´t work. I appreciate any kind of help or suggestions.
function standardDeviation(array) {
let newArray = [];
for (let i = 0; i < array.length; i++) {
let tempArray = [];
const arrAvg = tempArray =>
tempArray.reduce((a, b) => a + b, 0) / tempArray.length;
newArray += tempArray;
for (let j = array[i]; (j = array[i + 5]); i++) {
tempArray += array[j];
}
}
console.log(newArray);
return newArray;
}
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
standardDeviation(arr);
You could slice a given array and take only five elements for getting an average.
function standardDeviation(array) {
const arrAvg = tempArray => tempArray.reduce((a, b) => a + b, 0) / tempArray.length;
return array.map((_, i, a) => arrAvg(a.slice(i, i + 5)));
}
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
console.log(standardDeviation(arr));
You could try using the slice() function of array element.
// simulated loop index
var curr_index_pos = 3;
// entire array
var array_full = [1,2,3,4,5,6,7,8,9,10];
// array with 5 next values from "curr_index_pos"
var array_5 = array_full.slice(curr_index_pos,curr_index_pos+5);
var sum = 0;
for( var i = 0; i < array_5.length; i++ ) {
sum += parseInt( array_5[i] );
}
var avg = sum/array_5.length;
console.log("array_5", array_5);
// [4,5,6,7,8]
console.log("sum", sum);
// 30
console.log("avg", avg);
// 6
I want to add an array add up.
Let's say there's an array of [7, 1, 21, 70]
On a an array index of 0, it would just be 7. On an array index of 1, I want it to be 7 + 1 (8). Array index 2, 7 + 1 + 21 (29). Array index 3 7 + 1 + 21 + 70 (99).
This is my current code:
var pot = {
'id': 1,
'name': ['stalin', 'hitler', 'mao', 'kim jong-il'],
'amount': [50, 10, 150, 500],
'percentages': new Array()
}
var random = Math.random()*100;
var random = String(random).split(".")[0];
console.log(random);
function potTotal(amounts) {
var sum = 0;
for (var key in amounts) {
sum += pot['amount'][key];
}
return sum;
}
function potPercentage(total, amounts) {
for (var key in amounts) {
var percentage = amounts[key] / total * 100;
var percentage = String(percentage).split(".")[0];
var percentage = Number(percentage);
pot['percentages'].push(percentage);
}
}
potPercentage(potTotal(pot['amount']), pot['amount']);
function ranging(total, percentages) {
console.log(percentages);
for(var i = 0; percentages < i; i++) {
console.log(percentages[i]);
}
}
//[7, 1, 21, 70]
ranging(random, pot['percentages']);
for (var key in pot['percentages']) {
console.log(key);
console.log(pot['percentages'][key]);
}
The results of which return:
69
[ 7, 1, 21, 70 ]
0
7
1
1
2
21
3
70
reduce is the function defined to do this kind tasks.
const arr = [7, 1, 21, 70].reduce((acc, el, i) => [...acc, (acc[i-1] || 0) + el], []);
console.log(arr);
Basically you are looking for prefix sum method, try the following:
var arr = [7, 1, 21, 70];
for(var i = 1; i < arr.length; i++){
arr[i] += arr[i-1];
}
console.log(arr);
For Reference : Prefix sum
A simple forEach() will do for you:
var arr = [7, 1, 21, 70];
arr.forEach((item, index) => {
if(index - 1 > -1){
arr[index] += arr[index-1];
}
});
console.log(arr);
Just iterate with a for loop and add the previous item
let items = [1,2,3,4,5,6,7];
for (let i = 1; i < items.length; i++)
items[i] = items[i] + items[i-1];
You could use the reduce method on the array so that you don't bother managing index while doing the computation and also reduce will return you a brand new array, with the added benefit of not destroying your original array
var originalArray = [7, 1, 21, 70];
var addUp = (acc, curr, index) => {
if (index === 0) acc.push(curr);
else acc.push(acc[index-1] + curr);
return acc;
}
var computedArray = originalArray.reduce(addUp, []);
console.log(computedArray);
I like this as this is so easy to read and does not mutate the original array.
Mapping over an array gives you access to each item in that array one by one (just like a foreach loop) but it also creates a new array containing the return value from the callback.
function addConsecutives(nums) {
let sum = 0;
return nums.map(num => sum += num)
}
console.log(addConsecutives([7, 1, 21, 70]));
I am trying to write a function that returns the number x. y number of times. The function should be able to take in multiple 2d arrays. There will be only 2 elements per input array.
So for example: function([4,3][2,2][12,5])
//output should be exactly: 444, 22, 1212121212
I have solved most of the problem but I am stuck when x is a 2 digit number.
would appreciate some help in solving this. I must return the solution as a string with a comma (' ,') that separates the different arrays.
Here is my code as of now:
function repeatnumber(data){
var result = " ";
for (var i = 0; i < data.length; i++){
if (Array.isArray(data[i])){
var x = data[i][0]
var y = data[i][1]
for(var j = 1; j <= y; j++){
result = result + x;
}
}
}
var number = result
var answer = number.match(/(\d)\1*/g)
return console.log(answer);
}
repeatnumber([[10, 2][11,1]])// DOESN'T WORK!! output must be: 1010,11
repeatnumber([[1, 2], [2, 3]]) //works
repeatnumber([[1, 4], [3, 6], [9, 2]]) //works
You could check if you got a nested array and map new values and join later all arrays with comma.
function repeatnumber(array) {
return (Array.isArray(array[0]) ? array : [array])
.map(([value, length]) => Array.from({ length }, _ => value).join(''))
.join(', ');
}
console.log(repeatnumber([42, 7]));
console.log(repeatnumber([[10, 2], [11,1]]));
console.log(repeatnumber([[1, 2], [2, 3]]));
console.log(repeatnumber([[1, 4], [3, 6], [9, 2]]));
If you are using es6 this could be the simplest.
let repeatnumber = (inputArr) => {
return inputArr.map((inp) => `${inp[0]}`.repeat(inp[1]));
}
Here's one of the solution.
function repeatNumber(data) {
var results = '';
data.forEach(function(arr) {
for(var i = 0; i< arr[1]; i++) results += arr[0].toString();
results += ',';
})
return results.substring(0, results.length - 1);
}
console.log(repeatNumber([[10, 2], [11,1]]));
console.log(repeatNumber([[1, 2], [2, 3]]));
console.log(repeatNumber([[1, 4], [3, 6], [9, 2]]));
As you've noticed, regex isn't the best option. You're making the question a lot more difficult than it needs to be. You can just make an array of each of those strings and then join them together. Also, more descriptive variable names will go a long way for you.
let data = [[10,2], [11,1]]
function repeatNumber(data) {
let resultArray = []
for (let i=0; i < data.length; i++) {
let num = data[i][0]
let times = data[i][1]
let newString = ""
for (let j=0; j < times; j++) {
newString += num
}
resultArray.push(newString)
}
return resultArray.join(", ")
}
console.log(repeatNumber(data))
If you're ok with a code golf solution, this will accomplish the same task:
data.map(([num, times]) => Array(times).fill(num).join("")).join(", ")
try this :
function repeatnumber(data) {
var result = "";
for (var i = 0; i < data.length; i++)
{
if (Array.isArray(data[i]))
{
var x = data[i][0]
var y = data[i][1]
for(var j = 1; j <= y; j++)
{
{
result = result + x;
}
}
}
if(i != data.length - 1)
result += " ";
}
var number = result
var split = number.split(" ");
//var answer = number.match(/(\d)\1*/g)
return console.log(split);
}
repeatnumber([[10, 2][11,1]]) should be repeatnumber([[10, 2],[11,1]]);
ES6 Solution
const repeat = (arr) => {
arr.map( v => {
const str = new Array(v[1] + 1).join(v[0]);
console.log(str); // save this in array or wherever u want.
})
};
repeat([[1, 4], [3, 6], [9, 2]])
You are missing a comma between two arrays, make it
repeatnumber([[10, 2],[11,1]])
Also, your regex won't work properly when you are adding two digit number, change your logic as
function repeatnumber(data)
{
var answer = [];
for (var i = 0; i < data.length; i++)
{
if (Array.isArray(data[i]))
{
var x = data[i][0]
var y = data[i][1]
result = "";
for(var j = 1; j <= y; j++)
{
result = result + x;
}
answer.push(result)
}
}
return answer;
}
Demo
function repeatnumber(data) {
var answer = [];
for (var i = 0; i < data.length; i++) {
if (Array.isArray(data[i])) {
var x = data[i][0]
var y = data[i][1]
result = "";
for (var j = 1; j <= y; j++) {
result = result + x;
}
answer.push(result)
}
}
return answer;
}
console.log(repeatnumber([
[10, 2],
[11, 1]
])) ;
console.log(repeatnumber([
[1, 2],
[2, 3]
])) ;
console.log(repeatnumber([
[1, 4],
[3, 6],
[9, 2]
])) ;
Edit
Or a more concise method using fill and reduce
function repeatnumber(data)
{
return data.map( s => Array( s[1] ).fill( "" ).reduce( (a,c) => a + s[ 0 ], "" ) )
}
Or using fill and join
function repeatnumber(data)
{
return data.map( s => Array( s[1] + 1 ).fill( "" ).join( s[ 0 ] ) )
}
Small code that works,
// iterate > create array and join with char > join parent array with comma
function repeatnumber(data){
if(!data || data.length < 1) return [];
return data.map(arr => Array(arr[1] + 1).join(arr[0])).join(',');
}
A better approach, thanks to Ariz
function repeatnumber(data) {
if (!data || data.length < 1) return [];
return data.map((arr) => `${arr[0]}`.repeat(arr[1])).join(',');
}
No creation of an extra array, so huge repetitions can be done with ease.
Single pass by nested template literals and .reduce() working hand to hand.
var a = [[10, 2], [11,1]],
b = [[1, 2], [2, 3]],
c = [[1, 4], [3, 6], [9, 2]],
f = a => a.reduce((r,[v,c],i) => `${i ? `${r},`:``}${`${v}`.repeat(c)}`,``);
console.log(f(a));
console.log(f(b));
console.log(f(c));
I am new to JavaScript, and I have an array which contains numbers.
var arr = [2,4,8,1,5,9,3,7,6];
How can I sort it using a native for loop in JavaScript?
I know sort function is available, but I want it through for loop.
The output should be:
var res = [1,2,3,4,5,6,7,8,9];
var Arr = [1, 7, 2, 8, 3, 4, 5, 0, 9];
for (var i = 1; i < Arr.length; i++)
for (var j = 0; j < i; j++)
if (Arr[i] < Arr[j]) {
var x = Arr[i];
Arr[i] = Arr[j];
Arr[j] = x;
}
console.log(Arr);
I would do something like this...
var input = [2,3,8,1,4,5,9,7,6];
var output = [];
var inserted;
for (var i = 0, ii = input.length ; i < ii ; i++){
inserted = false;
for (var j = 0, jj = output.length ; j < jj ; j++){
if (input[i] < output[j]){
inserted = true;
output.splice(j, 0, input[i]);
break;
}
}
if (!inserted)
output.push(input[i])
}
console.log(output);
Maybe there are more efficient ways, but if you want to use the for loop, it's my first idea...
First create an empty array where the sorted numbers will be pushed into.
let sorted = [];
Secondly, create a very large amount of numbers that none of the numbers of the array can match. This number will be used for the very first comparison to determine which number of the array is smaller.
let comparison = 9000000000;
Create a for loop.
This loop will have another loop inside of it. The inner loop will check for the smallest number in a given array, and once the smallest number is gotten, it will be push into the empty array we created. The smallest number will also be removed from the initial array and then the array will run again.
for(a = 0; a < arr.length; a++){
//This inner loop fetches the smallest number.
for(b = 0; b < arr.length; a++){
if(comparison > arr[b]){
comparison = arr[b];
}
}
// The smallest number is assigned to comparison
// Now it being pushed to the empty array
sorted.push(comparison);
// Remove the smallest number from the initial array
let indexOfSmallNumber = arr.indexOf(comparison);
arr.splice(indexOfSmallNumber, 1);
// Set the comparison back to 9000000000;
comparison = 90000000000;
a = -1;
// Here, "a" is our main loop index counter and we are
// setting it to -1 because we don't want it to change
// to 2 by default, doing this will make the loop run
// forever until the initial array is empty.
}
let arr = [4, 2, 5, 1]
let temp;
function converter(arr) {
for(let i=0; i<arr.length; i++) {
for (let j=i+1; j<arr.length; j++) {
if(arr[i] > arr[j]) {
temp = arr[i]
arr[i] = arr[j]
arr[j] = temp
}
}
}
return arr
}
const newArr = converter(arr)
console.log(newArr)
Use:
let s = [4, 6, 3, 1, 2];
for (let i = 0; i < s.length;) {
if (s[i] > s[i + 1]) {
let a = s[i];
s[i] = s[i + 1];
s[i + 1] = a;
i--;
}
else {
i++;
}
}
This is a sorting algorithm which has a best time complexity of O(n) and the worst time of O(n^2).
This code checks for each number, and then compares to all numbers on the left side.
To check the time it takes each code to run, you can also use this code below:
let start = process.hrtime.bigint()
let end = process.hrtime.bigint()
console.log(end - start) // This measures the time used in nano seconds.
Also for microseconds, you can use this performance.now().
Here there is a very simple solution that uses a temporary array to store the values greater than the current one. Then it puts the current value between the lesser and the greater values:
var arr = [2,4,8,1,5,9,3,7,6];
var res = [];
for (const c of arr) {
let tmp = [];
while (c < res[res.length-1]) {
tmp.unshift(res.pop());
}
res = [...res, c, ...tmp];
}
const numberArr = [5, 9, 2, 8, 4, 10, 1, 3, 7, 6];
function sortedFunction(arr) {
let sortedArr = [];
for (let i = 0; i < arr.length; i++) {
for (let j = i + 1; j < arr.length; j++) {
let n = 0;
if (arr[i] > arr[j]) {
n = arr[i];
arr[i] = arr[j];
arr[j] = n;
}
}
sortedArr.push(arr[i]);
}
return sortedArr;
}
sortedFunction(numberArr);
Under the JavaScript array sort section of W3Schools it talks about how to compare a value in an array with the others and then order them based on the values being returned. I updated the code to use a for loop to sort values.
// Ascending points
var points = [5.0, 3.7, 1.0, 2.9, 3.4, 4.5];
var output = [];
var i;
for (i = 0; i < points.length; i++) {
points.sort(function (a, b) {
return a - b
});
output += points[i] + "<br>";
}
console.log(output);
// Descending points
var points = [5.0, 3.7, 1.0, 2.9, 3.4, 4.5];
var output = [];
var i;
for (i = 0; i < points.length; i++) {
points.sort(function (a, b) {
return b - a
});
output += points[i] + "<br>";
}
console.log(output);
const array = [12, 3, 45, 61, 23, 45, 6, 7];
function sortArray(array) {
for (var i = 0; i < array.length; ++i) {
for (var j = 0; j < array.length - 1 - i; ++j) {
if (array[j] > array[j + 1]) {
[array[j], array[j + 1]] = [array[j + 1], array[j]];
}
}
}
return array;
}
console.log(sortArray(array));
Here are the two solutions for the same algorithm:
Solution 1:
We can directly use JavaScript functions:
let arr = [2, 4, 8, 1, 5, 9, 3, 7, 6]
const changeOrder = (arr) => {
return arr.sort((a, b) => a - b)
}
let result = changeOrder(arr);
console.log(result) // [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
Solution 2:
We can use a JavaScript for loop for doing the same
let arr = [2, 4, 8, 1, 5, 9, 3, 7, 6]
const changeOrder = (arr) => {
for(let i=1; i< arr.length; i++) {
for(let j=0; j < i; j++) {
if(arr[i] < arr[j]) {
let x = arr[i]
arr[i] = arr[j]
arr[j] = x
}
}
}
return arr;
}
let result = changeOrder(arr);
console.log(result) // [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
An improvement to previous answer
for (let i = 0; i < arr.length; i++) {
for (let j = 0; j < arr.length - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
let temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
I am splitting an array into two arrays arr1 & arr2. Then I want to sum the values and bind into another array like arr3. How can I do this?
var arr1 = [1,2,3,4]
var arr2 = [2,3,4,4]
var arr3 = [3,5,7,8]
this works fine with static arrays, but my problem is
var TotalOfArray = [];
var temparray = [];
for (i = 0, j = x.length; i < j; i += chunk) {
temparray = x.slice(i, i + chunk);
if (temparray.length == chunk) {
console.log("before loop: "+TotalOfArray.length);
if (TotalOfArray.length == 0) {
for (i in temparray) {
TotalOfArray[i] = temparray[i];
}
console.log("after loop: "+TotalOfArray.length);
} else {
for (i in temparray) {
TotalOfArray[i] = TotalOfArray[i] + temparray[i];
}
}
}
}
As you can see, x will be the main array which I am splicing into a temparray array, so every time it will splice with array length 31 and than I want to do sum, chunk = 31 as of now. But it's not going into ELSE part.
Equal Length Arrays:
This is just a more simple version, that assumes equal lengths from both arrays. For a solution that works with variable length arrays, read further on.
var arr1 = [1, 2, 3, 4];
var arr2 = [2, 3, 4, 4];
var arr3 = arr1.map(function(a, i) {
return a + arr2[i];
});
console.log(arr3);
Variable Length Arrays:
This is going to be a more robust solution regardless. But it finds the array with the most values in it, and uses that for the map. Then, if undefined values are found in the other array, it will use 0 as the other number.
var arr1 = [1, 2, 3, 4];
var arr2 = [2, 3, 4, 4, 5];
var sorted = [arr1, arr2].sort((a, b) => b.length - a.length);
var arr3 = sorted[0].map(function(a, i) {
return a + (sorted[1][i] || 0);
});
console.log(arr3);
Use for loop:
var arr1 = [1,2,3,4]
var arr2 = [2,3,4,4]
var arr3 = []
for (i in arr1) { arr3[i] = arr1[i] + arr2[i]; }
console.log(arr3)
If two arrays have equal length you can can use Array.prototype.map();
var data1 = [1,2,3,4],
data2 = [2,3,4,4],
result;
result = data1.map(function(value, i){
return value + data2[i];
});
console.log(result);
var arr1 = [1,2,3,4]
var arr2 = [2,3,4,4]
var arr3 = []
for (var i = 0; i < arr1.length; i++) {
arr3.push(arr1[i] + arr2[i])
}
Assuming arr1 and arr2 have the same length.