Related
I have a one-dimensional array of integer in JavaScript that I'd like to add data from comma separated string, Is there a simple way to do this?
e.g : var strVale = "130,235,342,124 ";
? "123,87,65".split(",").map(Number)
> [123, 87, 65]
Edit >>
Thanks to #NickN & #connexo remarks!
A filter is applicable if you by eg. want to exclude any non-numeric values:
?", ,0,,6, 45,x78,94c".split(",").filter(x => x.trim().length && !isNaN(x)).map(Number)
> [0, 6, 45]
You can use split() to get string array from comma separated string. If you iterate and perform mathematical operation on element of string array then that element will be treated as number by run-time cast but still you have string array. To convert comma separated string int array see the edit.
arr = strVale.split(',');
Live Demo
var strVale = "130,235,342,124";
arr = strVale.split(',');
for(i=0; i < arr.length; i++)
console.log(arr[i] + " * 2 = " + (arr[i])*2);
Output
130 * 2 = 260
235 * 2 = 470
342 * 2 = 684
124 * 2 = 248
Edit, Comma separated string to int Array In the above example the string are casted to numbers in expression but to get the int array from string array you need to convert it to number.
var strVale = "130,235,342,124";
var strArr = strVale.split(',');
var intArr = [];
for(i=0; i < strArr.length; i++)
intArr.push(parseInt(strArr[i]));
You can use the String split method to get the single numbers as an array of strings. Then convert them to numbers with the unary plus operator, the Number function or parseInt, and add them to your array:
var arr = [1,2,3],
strVale = "130,235,342,124 ";
var strings = strVale.split(",");
for (var i=0; i<strVale.length; i++)
arr.push( + strings[i] );
Or, in one step, using Array map to convert them and applying them to one single push:
arr.push.apply(arr, strVale.split(",").map(Number));
just you need to use couple of methods for this, that's it!
var strVale = "130,235,342,124";
var resultArray = strVale.split(',').map(function(strVale){return Number(strVale);});
the output will be the array of numbers.
The split() method is used to split a string into an array of substrings, and returns the new array.
Syntax:
string.split(separator,limit)
arr = strVale.split(',');
SEE HERE
You can split and convert like
var strVale = "130,235,342,124 ";
var intValArray=strVale.split(',');
for(var i=0;i<intValArray.length;i++{
intValArray[i]=parseInt(intValArray[i]);
}
Now you can use intValArray in you logic.
Solution:
var answerInt = [];
var answerString = "1,2,3,4";
answerString.split(',').forEach(function (item) {
answerInt.push(parseInt(item))
});
All of the given answers so far create a possibly unexpected result for a string like ",1,0,-1,, ,,2":
",1,0,-1,, ,,2".split(",").map(Number).filter(x => !isNaN(x))
// [0, 1, 0, -1, 0, 0, 0, 2]
To solve this, I've come up with the following fix:
",1,0,-1,, ,,2".split(',').filter(x => x.trim() !== "").map(Number).filter(x => !isNaN(x))
// [1, 0, -1, 2]
Please note that due to
isNaN("") // false!
and
isNaN(" ") // false
we cannot combine both filter steps.
This is an easy and quick solution when the string value is proper with the comma(,).
But if the string is with the last character with the comma, Which makes a blank array element, and this is also removed extra spaces around it.
"123,234,345,"
So I suggest using push()
var arr = [], str="123,234,345,"
str.split(",").map(function(item){
if(item.trim()!=''){arr.push(item.trim())}
})
There are good solutions in this post but I would like to add one more. Instead of using filter and map I would suggest to use reduce to iterate through all the items just once.
Also I will compare it with the use of a regex looking for digits. Please evaluate which method fits your needs. Here are the examples:
const strA = ',1,0,-2,a3 , 4b,a5b ,21, 6 7,, 8.1'
const arrayOfNumbersA = strA.split(',').reduce((acc, val) => val && !Number.isNaN(+val) ? acc.push(+val) && acc : acc, [])
console.log(arrayOfNumbersA)
// => [1, 0, -2, 21, 8.1] - As you can see in the output the negative numbers
// do work and if the number have characters before or after
// the numbers are removed from since they are treated like NaN.
// Note: in this case the comma is the delimiting each number that will be evaluated in the reduce
const arrayOfNumbersB = strA.match(/[\d.]+/g).map(Number)
console.log(arrayOfNumbersB)
// => [1, 0, 2, 3, 4, 5, 21, 6, 7, 8.1] - As you can see in the output the negative numbers
// are transformed to positives and if the number have characters before or after
// the numbers placed any way.
//Note: that in this case the regex is looking for digits no matter how they are separated.
// FYI: seeing all the steps using the reduce method
const arrayOfNumbersC = strA.split(',').reduce((acc, val) => {
if(val && !Number.isNaN(+val)) {
acc.push(+val)
}
return acc
}, [])
console.log(arrayOfNumbersC)
// => [1, 0, -2, 21, 8.1]
In order to also take string value and avoid crushing we can solve it this way
let strVale = "130,235,342,124 ";
let unformattedArray =strVale.split(',');
const formatArray = (unformattedArray) => {
if (unformattedArray.map(Number).includes(NaN)) {
return unformattedArray;
}
else {
return unformattedArray.map(Number);
}
}
//then every time we want to format we call our function to format for us
console.log(formatArray(unformattedArray));
// or asign a value
let foramttedArray = formatArray(unformattedArray);
var num_list = [1, 2, 3, 4];
function num_order(a, b) {return b-a; }
num_list.sort(num_order);
I've been through blogs and i have searched on this topic but to no avail. All describe this function to be sorting in descending order but none specify how does that happen..
For example, what values are stored in the parameters a and b and how are these values assigned.. Finally what results the function passes and how does sort method do to those values.. Any help would be appreciated..
Let me specify that there is a post similar to this but the answer in that post is not clear.. One of the user has provided a link here which makes it much clearer
The parameter you pass to the sort method is the comparison function. It will define the order the elements are sorted.
To see what values are being passed to the parameters a and b. Try this in your console:
var num_list = [1, 2, 3, 4];
num_list.sort(function(a, b) {
debugger;
return b-a;
})
MDN has good documentation on the compare function: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
Have a look at any sort algorithm : at some point they need to compare two elements of the array.
The sort function of most Browsers is heapsort or quicksort, but i will take bubble sort as an example of a sort algorithm :
n = array size
repeat
swapped = false
for i= 0 to n-2
if array [i] > array [i+1] then
swap ( array [i] , array [i+1] )
swapped = true
end for
n = n -1
until swapped = false
we can easily rewrite the comparison to use a comparison function :
n = array size
repeat
swapped = false
for i= 0 to n-2
a = array [i]
b = array [i+1]
if compareFunction(a,b) > 0 then
swap ( array [i] , array [i+1] )
swapped = true
end for
n = n -1
until swapped = false
with :
compareFunction (a,b)
return a-b
So the comparison function is just a function that returns an integer that reflect the items order.
If two elements are the same => the function returns 0, first is bigger => returns >0, second is bigger => returns <0.
Using a comparison function allows to sort any kind of array (i.e. an array containing any kind of item), while still using the very same sort algorithm as the one used for integer sort.
I have a one-dimensional array of integer in JavaScript that I'd like to add data from comma separated string, Is there a simple way to do this?
e.g : var strVale = "130,235,342,124 ";
? "123,87,65".split(",").map(Number)
> [123, 87, 65]
Edit >>
Thanks to #NickN & #connexo remarks!
A filter is applicable if you by eg. want to exclude any non-numeric values:
?", ,0,,6, 45,x78,94c".split(",").filter(x => x.trim().length && !isNaN(x)).map(Number)
> [0, 6, 45]
You can use split() to get string array from comma separated string. If you iterate and perform mathematical operation on element of string array then that element will be treated as number by run-time cast but still you have string array. To convert comma separated string int array see the edit.
arr = strVale.split(',');
Live Demo
var strVale = "130,235,342,124";
arr = strVale.split(',');
for(i=0; i < arr.length; i++)
console.log(arr[i] + " * 2 = " + (arr[i])*2);
Output
130 * 2 = 260
235 * 2 = 470
342 * 2 = 684
124 * 2 = 248
Edit, Comma separated string to int Array In the above example the string are casted to numbers in expression but to get the int array from string array you need to convert it to number.
var strVale = "130,235,342,124";
var strArr = strVale.split(',');
var intArr = [];
for(i=0; i < strArr.length; i++)
intArr.push(parseInt(strArr[i]));
You can use the String split method to get the single numbers as an array of strings. Then convert them to numbers with the unary plus operator, the Number function or parseInt, and add them to your array:
var arr = [1,2,3],
strVale = "130,235,342,124 ";
var strings = strVale.split(",");
for (var i=0; i<strVale.length; i++)
arr.push( + strings[i] );
Or, in one step, using Array map to convert them and applying them to one single push:
arr.push.apply(arr, strVale.split(",").map(Number));
just you need to use couple of methods for this, that's it!
var strVale = "130,235,342,124";
var resultArray = strVale.split(',').map(function(strVale){return Number(strVale);});
the output will be the array of numbers.
The split() method is used to split a string into an array of substrings, and returns the new array.
Syntax:
string.split(separator,limit)
arr = strVale.split(',');
SEE HERE
You can split and convert like
var strVale = "130,235,342,124 ";
var intValArray=strVale.split(',');
for(var i=0;i<intValArray.length;i++{
intValArray[i]=parseInt(intValArray[i]);
}
Now you can use intValArray in you logic.
Solution:
var answerInt = [];
var answerString = "1,2,3,4";
answerString.split(',').forEach(function (item) {
answerInt.push(parseInt(item))
});
All of the given answers so far create a possibly unexpected result for a string like ",1,0,-1,, ,,2":
",1,0,-1,, ,,2".split(",").map(Number).filter(x => !isNaN(x))
// [0, 1, 0, -1, 0, 0, 0, 2]
To solve this, I've come up with the following fix:
",1,0,-1,, ,,2".split(',').filter(x => x.trim() !== "").map(Number).filter(x => !isNaN(x))
// [1, 0, -1, 2]
Please note that due to
isNaN("") // false!
and
isNaN(" ") // false
we cannot combine both filter steps.
This is an easy and quick solution when the string value is proper with the comma(,).
But if the string is with the last character with the comma, Which makes a blank array element, and this is also removed extra spaces around it.
"123,234,345,"
So I suggest using push()
var arr = [], str="123,234,345,"
str.split(",").map(function(item){
if(item.trim()!=''){arr.push(item.trim())}
})
There are good solutions in this post but I would like to add one more. Instead of using filter and map I would suggest to use reduce to iterate through all the items just once.
Also I will compare it with the use of a regex looking for digits. Please evaluate which method fits your needs. Here are the examples:
const strA = ',1,0,-2,a3 , 4b,a5b ,21, 6 7,, 8.1'
const arrayOfNumbersA = strA.split(',').reduce((acc, val) => val && !Number.isNaN(+val) ? acc.push(+val) && acc : acc, [])
console.log(arrayOfNumbersA)
// => [1, 0, -2, 21, 8.1] - As you can see in the output the negative numbers
// do work and if the number have characters before or after
// the numbers are removed from since they are treated like NaN.
// Note: in this case the comma is the delimiting each number that will be evaluated in the reduce
const arrayOfNumbersB = strA.match(/[\d.]+/g).map(Number)
console.log(arrayOfNumbersB)
// => [1, 0, 2, 3, 4, 5, 21, 6, 7, 8.1] - As you can see in the output the negative numbers
// are transformed to positives and if the number have characters before or after
// the numbers placed any way.
//Note: that in this case the regex is looking for digits no matter how they are separated.
// FYI: seeing all the steps using the reduce method
const arrayOfNumbersC = strA.split(',').reduce((acc, val) => {
if(val && !Number.isNaN(+val)) {
acc.push(+val)
}
return acc
}, [])
console.log(arrayOfNumbersC)
// => [1, 0, -2, 21, 8.1]
In order to also take string value and avoid crushing we can solve it this way
let strVale = "130,235,342,124 ";
let unformattedArray =strVale.split(',');
const formatArray = (unformattedArray) => {
if (unformattedArray.map(Number).includes(NaN)) {
return unformattedArray;
}
else {
return unformattedArray.map(Number);
}
}
//then every time we want to format we call our function to format for us
console.log(formatArray(unformattedArray));
// or asign a value
let foramttedArray = formatArray(unformattedArray);
I'm looking to extract a subsection of a javascript array of objects based on a certain condition, e.g:
object.property == 2
I know that I could look through and build a new array from the ones that match, but I was wondering whether there was a shorthand for this.
You can use grep().
var arr = [ 1, 2, 3 ];
var subset = $.grep(arr,function(n,i){ return n >= 2 });
// subset = [2, 3]
Use http://api.jquery.com/filter/
e.g.
$(yourCollection).filter(function(){
return (this.property == 2);
});
EDIT:
jsFiddle with both approaches benchmarked: http://jsfiddle.net/StuperUser/6AfQj/
What is the best way to randomize part of the array in Javascript
For example, if I have 100 items in the array, what is the fast and efficient way of randomizing set of every 10 times. Items between 0 and 9 is randomize within data items[0] to items[9]. Items between 10 to 19 are randomize within data items[10] to items[19] and so on..
You can adjust the array shuffle method that is described here: http://jsfromhell.com/array/shuffle
It is based on Fisher-Yates (Knuth) algorithm (http://en.wikipedia.org/wiki/Fisher–Yates_shuffle).
I would just use the built in slice, concat and sort methods. Something like this.
function shuffle(arr, start, end) {
return arr.slice(start, end).sort(function() { return .5 - Math.random(); }).concat(arr.slice(end));
};
That's the basic idea, you probably want to make an algorithm to slice every 10 elements, sort and rejoin the sets.
EDIT: Read comments below for why this solution may not be suitable for your needs.
I would split the 1 array into 10 subsets, then perform a shuffle algorithm of your choice on those subsets, and then recombine in the correct order.
The following shuffles the specified chunk of an array in place, as randomly as the environment's random number generator will allow:
function shuffleSubarray(arr, start, length) {
var i = length, temp, index;
while (i--) {
index = start + Math.floor(i * Math.random());
temp = arr[index];
arr[index] = arr[start + i];
arr[start + i] = temp;
}
return arr;
}
var a = [1, 2, 3, 4, 5, 6, 7, 8, 9];
alert( shuffleSubarray(a, 2, 5) );