I have two arrays, one with strings of large numbers and the other with the sums of the large numbers added together, is there any way where I can have the two arrays correspond with each other? Like to make location [2] in the first array correspond with the same location in the second array. More specifically, I originally establish the array of large numbers, and I've written a function that creates the second array giving me the sums of each numeral in the large numbers (ex. 123456789 in the first array would be 45 in the second array), but I need to be able to link the two arrays because the first array needs to work with any number of strings of numbers. (sorry if this is confusing; I'm just a little out of my depth on this.)
Here is the code I'm working on:
var theArray = ["585-777-7279", "922-901-8934", "112-211-4857", "994-934-9989"];
var plsWork = function() {
var theArrayTwo = theArray.join().replace(/-/g, "");
var theArrayThree = theArrayTwo.split(",").map(Number);
var phoneSum = theArrayThree.map(function (a) {
return Array.prototype.slice.call(a.toString()).map(Number).reduce(function(b,c) {
return b + c;
});
})
phoneSum.sort().reverse();
console.log(phoneSum);
};
Basically, I just want to know if there's a way that I can get the two arrays (the original and the one created in the function) to correspond. Ideally, I would like to be able to have it where I can show that the smallest sum corresponds with the number from the first array.
If you already have the two arrays, the best way to relate one to another would be to create an array of objects as suggested by #webdeb.
If instead you have the array of large numbers and then all you want is to create a second array that in each index contains the sum of all the digits of the number in the first array, than I would use the following code:
var large_numbers = [1234, 2345, 3456];
function sumDigits(number) {
var digitsArray = [],
string = number.toString(); // convert number to string
for (let i = 0; i < string.length; i++) {
// push the numbers to a temporary array so that
// I can sum them one by one later
digitsArray.push(parseInt(string[i], 10));
}
// return the sum of all the elements of the digitsArray
return tempArray.reduce(function(prev, curr) {
return prev + curr;
})
}
var sumsArray = large_numbers.map(sumDigits); // -> [10, 14, 18]
The sumsArray contains in the sum of all the digits of the number in the large numbers array in the same index.
Related
This question already has answers here:
Split array into chunks
(73 answers)
Closed 1 year ago.
I have the js code below:
let splits = 23;
let outer_bound_value = 0;
let data = //this is an array of a large number of predefined objects (10,200+)
for (i = 0; i < data.length; i = i + outer_bound_value) {
outer_bound_value = data.length / splits;
let split_arr = array.slice(i, i + outer_bound_value);
}
The desired outcome of this code is to be able to split the mega array into smaller arrays based on what the value of splits is (if splits is 5, split the large array into 5 sections). I think the approach I have above works but it is dependent on splits being able to be go into the length of the object and it could cause outofbounds errors. Anyone have a more efficient way to do what I am trying to do?
First divide the array by the amount of splits you want.
Normally I would use a new Set() as it is much faster than splitting arrays with slice however I have no idea what type of data you have in your arrays, Sets are unique when it comes to ints.
we use recursion and destructuring to return the sliced array. this will return you multiple arrays into the array length/splits.
const splits = 23;
const data = new Array(10000);
const chunkValue = Math.floor(data.length/splits);
function chunkArray(array, size) {
if(array.length <= size){
return [array]
}
return [array.slice(0,size), ...chunkArray(array.slice(size), size)]
}
const newArrays = chunkArray(data, chunkValue)
I want to sort an array of phone numbers and have the length of the array outputted based on areacode. For example:
var nums = [
8881756223,
8881742341,
9187221757,
...,
]
there are a lot more entries than that (roughly 1300) and its already in numerical order. However, what I want it to do is:
1. look at the first 3 numbers of the first entry
2. look at the next entries first 3 numbers
3. if they are different, then splice the array, console.log new array.length
and console.log that area code
so for example, the first two numbers in the array i provided will be spliced into their new array, and the console output will be:
areacode: 888, length: 1
areacode: 918, length: 0
I know the regex to search for the first the numbers, but I don't exactly know how to splice them into their own arrays...Like i know, use splice, but comparing the two with logic statements, I've never had to do something like that before while using a regular expression.
what I have so far is this:
const patt = new RegExp('^\d{3}')
var newArr = nums.filter(x => patt)
for (var i = 0; i < newArr.length; i++)
console.log(newArr[i])
but this is spitting out the full number, not the area code its self. Of course ill be adding the logic to sort after i get it to just spit out area codes.
I suggest using
nums.map(x => ("" + x).replace(/^(\d{3})[^]*/, '$1'))
Here,
"" + x will coerce the number to string
.replace(/^(\d{3})[^]*/, '$1') will remove all chars keeping the first 3 digits (or the whole string upon no match).
JS Demo:
var nums = [
8881756223,
8881742341,
9187221757,
1
];
var res = nums.map(x => ("" + x).replace(/^(\d{3})[^]*/, '$1'));
console.log(res);
you can try this
var nums = [
8881756223,
8881742341,
9187221757
]
var prefixes = nums.map(x=>(x+"").substr(0,3));
var votes = prefixes.reduce(
(votes, curr) => {
if(votes[curr]) votes[curr]++;
else {votes[curr] =1;}
return votes;
}, {});
var ans = Object.keys(votes).map(x => ({areacode:x, length:votes[x]}));
console.log(ans);
ans will hold the value you require
vote counting technique i used is explained here https://igghub.github.io/2017/01/15/useful-js-reduce-trick/
I have two 1D arrays and I want to fill them with 10 unique random x,y values in Processing.
For example:
x y
- -
3, 9
2, 4
6, 2
7, 5
My arrays are:
Table1 for the X values and
Table2 for the Y values.
My issue is if the number 3,9 exists already I don't want 9,3 to be stored in the arrays.
I can identify when x,y value (or y,x) already exists but once I replace it I cannot check if the new generated random number exist in the previous indexes.
This is what I have tried so far. However if 3 values aldready exists, the arrays Table1 and Table2 will store only 7 values instead of 10.
for (int i=0; i<10; i++) {
x=(int)random(6);
y=(int)random(6);
if ((Table1[i] != x && Table2[i] != y) || (Table1[i] != y && Table2[i] != x))
{
Table1[i] = x;
Table2[i] = y;
}
Any ideas how to control that?
I can think about only two ways of achieving it, and none is ideal.
Check if the numbers you generated already exists, and if it's the case, generate anothers until you get a unique combination. It could be expensive with a small range of possibilities, because it's random, and if you're very unlucky you could even end in an infinite loop...
Create an array containing every possible combination. Then, instead of generating random numbers, you'll generate a random index into this array (an integer in [0;array.length[). After that, you'll have to remove the choosen combination from the array (that way it won't be available for the next loop), and the inverse of it (if you picked (9;3), you have to remove (9;3) AND (3;9)).
I have this code that might help you,
first declare your arrays :
var a = [];
var b = [];
then you can call a function that does everything for you
fill(a,b)
The definition of this function should be something like this :
function fill(a, b) {
var arr = [];
while(arr.length<10) {
var pair = randomPair();
if (arr.indexOf(pair.join(','))==-1 || arr.indexOf(pair.reverse().join(','))==-1) {
a.push(pair[0]);
b.push(pair[1]);
arr.push(pair.join(','));
}
}
}
then the defintion of other used function is :
function randomPair () {
return [ parseInt(Math.random()*7) , parseInt(Math.random()*7) ]
}
so, obviously, the randomPair function returns 2 values x and y. the fill function tests if the pair already exists or not in normal order or reversed order. if not it's added both a, and b which are references to your main arrays;
I see no other option as to walk to the whole arrays again to check if they contains your new generated value(s).
I have got an array of the form:
['32 68', '56 78', '77 99']
I want to o/p another array which will contain the sum of each element in the index using JavaScript (NodeJS). Something like,
['100', '134', '176']
I tried to use .split("") but the double integer number again gets separated as separate digits. Is there any other way to solve this? Please not that, the i/p can be single digit number or double digit.
You'll want to get each item, split on a space (if exists) then add up the corresponding split. Something like this:
var origValues = ['32 68', '56 78', '77 99', '7'];
var addedValues = origValues.map(function(value) {
return value.split(' ')
.map(function(sArray) {
return parseInt(sArray);
})
.reduce(function(a, b) {
return a + b;
});
});
document.write(JSON.stringify(addedValues));
Note that this above example handles the case where you have a single digit inside your array value as well.
To provide some explanation as to what is happening...
You start off taking your original array and you are mapping a function on to each value which is what is passed into that function.
Inside that function, I am splitting the value by a space which will give me an array of (possibly) two values.
I then apply the map function again onto the array and parse each value in the array to an integer.
Last, I reduce the integer array with a summation function. Reduce applies an accumulator function to each item in the array from left to right so you will add up all your values. This result is returned all the way back up so you get your new array with your answers.
Kind of what it looks like in "drawing" form:
Start: origValues = ['32 68', '56 78', '77 99', '7']
Apply map (this will track one value): value = '32 68'
Apply the split: ['32', '68']
Map the parse integer function (I'm going to track both values): [32, 68]
Reduce: 32 + 68 = 100
I don't have time for an explanation (sorry) but, split + reduce will do it.
var arr = ['32 68', '56 78', '77 99'];
var sumArray = arr.map(function (s) {
return s.split(' ').reduce(function (a, b) {
return parseInt(a, 10) + parseInt(b);
});
});
document.write(JSON.stringify(sumArray));
You don't actually need map or anything. For each string we can .split, Numberify, and add.
secondArray[value] =
Number((firstArray[value].split(" "))[0]) +
Number((firstArray[value].split(" "))[1]);
Modifying this and turning this into a for loop, we get:
var arr2 = [];
for(var i = 0; i < arr.length; i ++){
arr2.push(
Number((arr[i].split(" "))[0]) +
Number((arr[i].split(" "))[1]));
}
arr = arr2;
I have a two-dimensional array in Google apps script that contains arrays of different lengths. I would like to set the values of the array in a spreadsheet. However, because the arrays inside it are different lengths, I receive an error that essentially says the range and the array height don't line up. I've listed an example of the structure of the array below.
I can make it work if I add empty values to each individual array so that they all match the length of the longest array. This seems like a workaround though. Is there another way that I can set the values of the two-dimensional array?
var array = [
[a],
[b,c],
[d,e],
[],
[f,g,h,i],
[],
[j,k],
]
No, you cannot. The dimensions must match.
What you can do if you have few "rows" with great length difference, is to set each row on it's own.
for( var i = 0; i < array.length; ++i )
sheet.getRange(i+1, 1, 1, array[i].length).setValues([array[i]]);
But that's just another workaround. But working on your array to make all lengths match and do a single setValues will probably perform better.
In case your real array has many rows, individual writes will be expensive. Redimensioning each row array is fairly straightforward due to the way js handles arrays. A pattern similar to one i use is:
function myFunction() {
var array = [
[1],
[2,2],
[3,5],
[],
[0,0,0,0],
[],
[0,0],
];
// get length of the longest row
var max = array
.slice(0)
.sort(function (a,b) {
return ( (a.length !== b.length) ? 1 : 0 );
})[0].length;
// arrays are zero indexed
var maxi = max-1;
// insert a pointer at max index if none exists
array = array
.map(function (a){
a[maxi] = a[maxi] || "";
return a;
});
Logger.log(array);
}