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]);
Related
I have 2 multidimensional arrays:
[[230.0], [10.0], [12.0]]
[[50.0], [60.0], [89.0]]
And am trying to sum each element together and keep the same array structure. So it should look like:
[[280.0], [70.0], [101.0]]
I tried this:
var sum = array1.map(function (num, index) {
return num + array2[index];
});
But I get this:
[23050, 1060, 1289]
Any help would be appreciated. Thanks.
The code, you use, takes only a single level, without respecting nested arrays. By taking na array with only one element without an index of the inner array and using an operator, like +, the prototype function toString is invoced and a joined string (the single element as string, without , as separator) is returned and added. The result is a string , not the result of a numerical operation with +.
You could take a recursive approach and check if the value is an array, then call the function again with the nested element.
function sum(a, b) {
return a.map((v, i) => Array.isArray(v) ? sum(v, b[i]) : v + b[i]);
}
console.log(sum([[230], [10], [12]], [[50], [60], [89]]))
Make it like this
var sum = array1.map(function (num, index) {
return parseInt(num) + parseInt(array2[index]);
});
You should have to make parseInt or parseFloat so it can convert string with them
STEPS
Iterate through every number in the array (array length).
Sum the objects of the same index in both of the arrays.
Push the sum into another array for the result. Use parseFloat if the input is string.
(Optional) use .toFixed(1) to set decimal place to have 1 digit.
const arr1 = [[230.0], [10.0], [12.0]]
const arr2 = [[50.0], [60.0], [89.0]]
let sum = []
for (let i = 0; i < arr1.length; i++){ // Assume arr1 and arr2 have the same size
let eachSum = parseFloat(arr1[i]) + parseFloat(arr2[i])
sum.push([eachSum.toFixed(1)])
}
console.log(sum)
You are trying to add two arrays structures inside the map function.
so one solution so you can see what is happening is this...
array1.map((a,i) => a[0] + array2[i][0])
screenshot from the console...
Inside map fn you should:
return parseInt(num) + parseInt(array2[index]);
This is happening because when you are trying to add them, these variable are arrays and not integers. So they are evaluated as strings and concatenated.
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 an array of character with commas separating them. I need to split an array but retain my comma inbetween each character.
See below for an example array:
var myArray = [a,,,b,c,d,,,]
There's a comma in there between the characters "a" and "b". I need to retain the comma when converting the array to a string.
The output string needs to resemble this:
a,bcd,
This is what i'm currently doing to retain the commas:
myArray.toString().replace(/,/g, "");
The Array's toString() method basically does a join(",") which is why you are getting the extra commas in your string.
Instead use join("") if you want to join the elements without the delimiter being added as part of the string
var myArray = ["a",",","b","c","d",",",]
document.body.innerText = myArray.join("");
How about you use :
var myArray = [a,,,b,c,d,,,];
var str = myArray.join();
This will give a string of array elements, preserving the commas.
if you want it to maintain the centre comma you should create your array as
var myArray = [a,",",b,c,d,",",];
this will then treat the middle comma in the set of 3 as a string containing that character rather than the array seperator
You could change your regex, to replace item,item for item item.
myArray.toString().replace(/([a-z,]),([a-z,])/g, "$1$2")
Basically you have a sparse array and want to extract only filled values and convert it to string ? Here is one, probably not the best, solution :
var myArray = ['a',',',',','b',',','c']
var resultArray = [];
for(var i = 0; i < myArray.length; i++){
if(myArray[i] !== ','){// allow 0, false, null values, but not undefined
resultArray.push(myArray[i]);
}
}
console.log(resultArray);
Working plnkr : http://plnkr.co/edit/55T6PGI9DuTlvy6k88hr?p=preview, check the console of your broswer.
If this is an actual array of strings and you wanted only those with actual values, you could use the filter() function to filter out any non-undefined ones :
// Your example array
var input = ['a',,,'b','c','d',,,];
// Remove any undefined elements
var output = input.filter(function(e){ return e; }); // yields ['a','b','c','d']
You could then use the join() function to create a string with your elements :
var result = output.join(); // yields "a,b,c,d"
Example Snippet
var input = ['a',,,'b','c','d',,,];
document.write('INPUT: ' + input + '<br />');
var output = input.filter(function(e){ return e; });
document.write('OUTPUT: ' + output);
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;
Got a string that is a series of 0 or 1 bit and an array of values, if in the string are characters that are set to 1, I need to return the corresponding value from the array.
example: mystring = "0101"; myarray =["A","B","C","D"]; then result = "B,D"
how can I get this result?
for(var i=0;i<mystring.length;i++){
if(mystring[i] != 0)
{
result = myarray[i];
}
}
Your code seems to work just fine, so you can just add another array and push the values on to that:
var result = [];
for (var i = 0 ...
result.push(myarray[i]);
http://jsfiddle.net/ExplosionPIlls/syA2c/
A more clever way to do this would be to apply a filter to myarray that checks the corresponding mystring index.
myarray.filter(function (_, idx) {
return +mystring[idx];
})
http://jsfiddle.net/ExplosionPIlls/syA2c/1/
Iterate through the characters in the binary string, if you encounter a 1, add the value at the corresponding index in the array to a temporary array. Join the temporary array by commas to get the output string.
I am not really sure if this is what you are looking for, but this returns the array of matches.
var result = [];
for(var i=0;i<mystring.length;i++){
if(parseInt(mystring[i]) !== 0 ) {
result.push(myarray[i]);
}
}
return result;
result = new Array();
for(var i=0;i