Javascript array sorting using regex - javascript

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/

Related

How can I tell whether or not an element inside an array is a number or a word (all elements in quotes)

Background information: I have an array
this.someArray = ["Word", "123", "456"]
Where this.someArray is dynamically written (the array elements are not hardcoded)
I need to convert all items that are numbers into numbers (yes I realise that this might not make sense, essentially this is the result I want - where the numbers don't have quotes but leave the words as they are):
["Word", 123, 456]
So the steps I've thought in terms of how to achieve this:
Find out whether each element in the array is a word or number
To achieve this I have:
isNumber(number) {
return !isNaN(parseFloat(number)) && !isNaN(number-0)
}
Use a for each loop to test whether each element is a word or number
this.someArray.forEach(element => {
this.isNumber(element)
});
Write an if statement (if the element in this.someArray is a number then remove the quotes from that element)
However I'm unsure of whether step 2 is actually the correct thing to do and I'm unsure of how to write step 3
Is there a way to accomplish this?
Further info:
This is what the dynamically generated array looks like:
This is the code:
this.someArray = this.biggerArray.map((n) => {
const data = [];
for (var key of Object.keys(n)) {
data.push(n[key].data);
}
return data;
});
I think a plain .map would be easier - check if the string is composed of all digits with a regular expression, and if so, call Number on it:
const arr = ["Word", "123", "456"];
const newArr = arr.map(
str => /^\d+$/.test(str) ? Number(str) : str
);
console.log(newArr);
^\d+$ means:
^ - start of string
\d+ - one or more digits
$ - end of string
If the numbers might contain decimals, then add an optional group for the decimal portion:
const arr = ["Word", "123", "456", '12.45'];
const newArr = arr.map(
str => /^\d+(?:\.\d+)?$/.test(str) ? Number(str) : str
);
console.log(newArr);
For the array of ['Process', '1287'], it still works as expected:
const arr = ['Process', '1287'];
const newArr = arr.map(
str => /^\d+(?:\.\d+)?$/.test(str) ? Number(str) : str
);
console.log(newArr);
This approach also works for decimals within quotes.
for (let i in someArray) {
if (parseFloat(someArray[i])) {
someArray[i] = parseFloat(someArray[i]);
}
}
This is a shorter way of doing it.
for (let i in someArray) {
parseFloat(someArray[i]) && (someArray[i] = parseFloat(someArray[i]));
}

creating new values by index in JS looping/arrays

I have an array of values:
let myArray = [ 'Ifmanwas',
'meanttos',
'tayonthe',
'groundgo',
'dwouldha',
'vegivenu',
'sroots' ]
I want to print out a new value for each item in the array so that the first item is a collection of all the characters at the zero index, the second is a collection of all the characters at the 1 index position, ect...
So for instance, the output of the first array would be "Imtgdvs" (all the letters at ("0"), the second would be "fearwer" (all the letters at index "1") ect...
I am very lost on how to do this and have tried multiple different ways, any help is appreciated.
For this simple attempt I have created an array of all the letters for the first instance:
function convertToCode(box) {
let arr = [];
for (i = 0; i < box.length; i++) {
let counter = i;
let index = box[counter];
let letter = index.charAt(0);
arr.push(letter);
}
console.log(arr);
}
convertToCode(myArray)
Thanks
The main issue in your example is this: index.charAt(0);. This will always get the first character, whereas you need a nested loop.
You could use Array.map() in combination with Array.reduce(), like so:
let myArray = ['Ifmanwas','meanttos','tayonthe','groundgo','dwouldha','vegivenu','sroots'];
const result = Array.from(myArray[0]) //Create an array as long as our first string
.map((l,idx) => //Update each item in that array...
myArray.reduce((out,str) => str[idx] ? out+str[idx] : out, "") //to be a combination of all letters at index [idx] from original array
);
console.log(result);
Note that this uses the first string in the array to decide how many strings to make, as opposed to the longest string.

javascript arrays relating/corresponding to each other

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.

Need to fetch the numbers from an array

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;

Arrays and strings in javascripts

Array1 = ['1,2,3']
How can I retrieve the numerical values by transforming it into non-string?
I've been trying parseInt, but I can only manage to get 1 as end-result.
Thanks.
If you start with an array containing a string, like in your example, you need to use split().
Example:
Array1 = ['1,2,3'];
var new_array = Array1[0].split(','); // new_array is ["1", "2", "3"]
for (var i = 0; i < new_array.length; i++) {
new_array[i] = parseInt(new_array[i]);
}
// new_array is now [1, 2, 3]
I would re-look why you're storing a comma separated string as an array element; but, if the reasoning is valid for your particular design, the question is do you have an array with more than one comma-separated string like this?
If you can, re-work your design to actually use an array of integers, so use:
var arr = [1,2,3];
instead of ['1,2,3'].
If you are storing comma separated strings as array elements, you can get each index as an array of integers using something like the following:
var array1 = ['1,2,3', '4,5,6,7'];
function as_int_array(list, index) {
return list[index].split(',').map(function(o) { return parseInt(o,10); });
}
console.log("2nd element: %o", as_int_array(array1, 1));
// => 2nd element: [4,5,6,7]
Hope that helps.
Generally parseInt() takes anything(most of the time string) as input and returns integer out of that input. If it doesn't get any integer then it returns NaN.
Why you are getting 1 !!!
Whenever you are using parseInt() it tries to read your input character by character. So according to your input
var Array1 = ['1,2,3'];
first it get's '1' and after that ',' (a comma, which is not a number) so it converts '1' into Integer and returns it as your result.
Solution of your problem :
var Array1 = ['1,2,3'];
//just displayed the first element of the array, use for or foreach to loop through all the elements of the array
alert(Array1[0].split(',')[0]);

Categories