I have a problem where i must take an array of strings(some numbers and some letters)and remove the Zeros, move them to the end, and return the array. The final result needs all of the numbers to be integers in the string.
I have tried mapping the array and parsing the integers. This works unless the array passed in has letters. then all the letters are relaced with NaN. I cant seem to set up a conditional that will only operate on the integers.
var final = ["a","b","c","d","1","1","3","1","9","9",0,0,0,0,0,0,0,0,0,0];
but it should be
var final = ["a","b","c","d",1,1,3,1,9,9,0,0,0,0,0,0,0,0,0,0]
I need to parse the integers but cant get map to do it without the problem i described earlier. I also tried using if statements too, with no help.
You could convert all numbers or try to convert and take the value, if the conversion is falsy.
var final = ["a", "b", "c", "d", "1", "1", "3", "1", "9", "9", 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
console.log(final.map(v => +v || v));
Zero safe approach.
var final = ["a", "b", "c", "d", "1", "1", "3", "1", "9", "9", "0", 0, 0, 0, 0, 0, 0, 0, 0, 0];
console.log(final.map(v => isNaN(v) ? v : +v));
You can try with isNaN() and Array.prototype.map() along with Conditional (ternary) operator:
var final = ["a","b","c","d","1","1","3","1","9","9",0,0,0,0,0,0,0,0,0,0];
final = final.map(i => isNaN(i) ? i : Number(i));
console.log(final);
You want to parse the number but return the original element if it's NaN using a conditional:
var final = array.map((x) => {
var n = parseInt(x, 10);
return !isNaN(n) ? x : n;
})
You could use this:
var input = ["0", "a", "0", "b", "0", "0", "c", "d", "0", 0, "0", "1", "0", "1","3","0", "1","9","9", "0"];
var final = [...input.filter(s => s != 0),
...input.filter(s => s == 0)
].map(s => isNaN(s) ? s : +s);
console.log(final);
Using map() and validating on isNaN().
["a","b","c","d","1","1","3","1","9","9",0,0,0,0,0,0,0,0,0,0]
.map(x => !isNaN(x) ? Number(x) : x)
Related
I have an array:
["1", "2","3","4","5"]
that I would like to change to:
[["1, 0 ,0 ,0"], ["2, 0, 0, 0"],["3,0,0,0"],["4,0,0,0"],["5,0,0,0"]]
I've tried to achieve this with the following code:
var arr1 = ["1", "2","3","4","5"];
var arr2 = [,"0", "0","0"];
for(var z=0; z<arr1.length; z++)
{
arr1[z] = arr1[z].concat(arr2);
console.log(arr1)
}
However, this doesn't achieve what I want and places commas between each item, which I think is because it is not a string? I've tried using .join too but I couldn't get that to work either.
Could someone point me in the right direction for this please? Thanks.
You first need to convert each element to array and then append the second array to the newly converted array element. The following code snippet would make it clear -
var arr1 = ["1", "2", "3", "4", "5"];
var arr2 = [ "0", "0", "0"];
for (var z = 0; z < arr1.length; z++) {
// First convert the element into a list
arr1[z] = [arr1[z]];
// Then append the second array to it
arr1[z] = arr1[z].concat(arr2);
// Another way -
//arr1[z].push(...arr2);
}
// Final array -
console.log(arr1);
Using Map() :
Another way to do it would be using map() as below -
var arr1 = ["1", "2", "3", "4", "5"];
var arr2 = [ "0", "0", "0"];
arr1 = arr1.map(el=>[el,...arr2]);
console.log(arr1);
Using ForEach()
You could also do it using forEach() method -
var arr1 = ["1", "2", "3", "4", "5"];
var arr2 = [ "0", "0", "0"];
// this will note mutate original arr1 and store result in res
let res = [];
// ... is the spread operator which will allows iterable objects to be expanded in place
arr1.forEach(el=>res.push([el,...arr2]));
// final result
console.log(res);
There's probably numerous other ways as well... These were just few I have listed. You could even do it using naive nested loops method if you don't know anything about map(), forEach(), or concat() / push() methods.
Hope this helps !
Please try the following example
const array = ["1", "2", "3", "4", "5"];
const output = array.map((entry) => [`${entry}, 0, 0, 0`]);
console.log(output);
See
Array.prototype.map()
Template literals (Template strings)
if it's set in stone, you can do
let arr = []
var arr1 = ["1", "2","3","4","5"];
var arr2 = ["0", "0","0"];
arr1.forEach(el=>arr.push([el, ...arr2]));
console.log(arr)
Use map to go through each of your element and append the array with zeros, transform it to a string and wrap in an array again which will hold one value
const a = ["1", "2", "3", "4", "5"]
const arr = [0, 0, 0, 0];
const res = a.map(x => [
[x, ...arr].join()
])
console.log(res)
Im trying to split all the numbers in a array:
var array_code = [116,101,120,116];
So i want the result to look like this: [1,1,6,1,0,1,1,2,0,1,1,6]
the code im working on right now looks like this:
var array_gesplit = new Array;
for(var i=0; i< array_code.length; i++){
console.log(array_code[i])
while (array_code[i]) {
array_gesplit.push(array_code[i] % 10 );
array_code[i] = Math.floor(array_code[i]/10);
}
}
The result im getting from this is:
[
6, 1, 1, 1,
0, 1, 0, 2,
1, 6, 1, 1
]
Who can help me ?
You can use Array.from() method for this:
var array_code = [116,101,120,116];
var result = Array.from(array_code.join(''), Number)
console.log(result)
Explanation:
array_code.join('') creates a string like "116101120116"
Array.from('116101120116') on this string results in new Array of strings like:
["1", "1", "6", "1", "0", "1", "1", "2", "0", "1", "1", "6"]
We can also use Array.from() with map function, so that we can convert all these string values to Number in one line like:
Array.from(array_code.join(''), x => Number(x))
Or, just Array.from(array_code.join(''), Number)
The above logic result is the required output.
You can use flatMap() and convert number to string and use built-in split() method.
var array_code = [116,101,120,116];
const res = array_code.flatMap(x => x.toString().split('').map(Number));
console.log(res)
You could take strings and map numbers.
var code = [116, 101, 120, 116],
result = code.flatMap(v => Array.from(v.toString(), Number));
console.log(result);
Here's a hack by using some details of the JavaScript language:
var array_code = [116, 101, 120, 116];
var array_string = JSON.stringify(array_code);
var array_parts = [].slice.call(array_string);
var parts = array_parts.slice(1, -1); // get rid of the square brackets
console.log(parts);
I am merging two sorted arrays in JavaScript. When I call function with two arrays having numbers it works fine, but when I call that function with strings then it does not work. Why?
function mergeSortedArrays(array1, array2) {
const mergedArray = [];
let array1Item = array1[0];
let array2Item = array2[0];
let i = 1;
let j = 1;
if (array1.length === 0) {
return array2;
}
if (array2.length === 0) {
return array1;
}
while (array1Item || array2Item) {
if (array2Item === undefined || array1Item < array2Item) {
mergedArray.push(array1Item);
array1Item = array1[i];
i++;
} else {
mergedArray.push(array2Item);
array2Item = array2[j];
j++;
}
}
console.log(mergedArray);
}
//working?
mergeSortedArrays([0, 3, 4, 12, 222], [3, 4, 6, 30]);
// not working why?
mergeSortedArrays(["0", "3", "4", "12", "222"], ["3", "4", "6", "30"]);
As said in the comments, strings in JS are compared lexically , so, "222" is smaller than "3".
A solution that I see that you can use, is this one:
After checking the arrays for nullity, then concat then into mergedArray, then use the JS function sort(), with the basic return of value1 - value2, that way it will sort the strings in the order you want, and also will work for numbers.
(Further read: Why is one string greater than the other when comparing strings in JavaScript?)
function mergeSortedArrays(array1, array2) {
let mergedArray = [];
if (array1.length === 0) {
return array2;
}
if (array2.length === 0) {
return array1;
}
mergedArray = array1.concat(array2)
mergedArray.sort(function(a, b) {
return a - b
})
console.log(mergedArray);
return mergedArray;
}
mergeSortedArrays([0, 3, 4, 12, 222], [3, 4, 6, 30]);
mergeSortedArrays(["0", "3", "4", "12", "222"], ["3", "4", "6", "30"]);
BUT, be knowing that this solution will only work as expected if the strings are representations of numbers ("1", "2",...), if it is something like "aa", "abc", "b" it probably won't work well and another solution may be needed. (something like this: https://stackoverflow.com/a/51169/8732818)
Sort for string works differently than numbers. Its based on the ASCII table values. For example "99" > "100000" return should return true
While trying to get all permutations using Heap's algorithm, I met trouble storing the results in array.
The result generated is (from console.log(arr);)
["1", "2", "3"]
["2", "1", "3"]
["3", "1", "2"]
["1", "3", "2"]
["2", "3", "1"]
["3", "2", "1"]
but only the last value is stored in the arr, and the array stored somehow is this (from console.log(JSON.stringify(allPermutations)); )
["3", "2", "1"]
["3", "2", "1"]
["3", "2", "1"]
["3", "2", "1"]
["3", "2", "1"]
["3", "2", "1"]
var allPermutations = [];
function swap(arr,index1,index2){
var dummy = arr[index1];
arr[index1] = arr[index2];
arr[index2] = dummy;
return arr;
}
function generate(n,arr){
if(n==1){
console.log(arr);
//result:
//["1", "2", "3"]
//["2", "1", "3"]
//["3", "1", "2"]
//["1", "3", "2"]
//["2", "3", "1"]
//["3", "2", "1"]
allPermutations.push(arr);
}else{
for(var i=0;i<n-1;i++){
generate(n-1,arr);
if( n%2 ==0){
arr = swap(arr,i,n-1);
}else{
arr = swap(arr,0,n-1);
}
}
generate(n - 1, arr);
}
}
generate(3,['1','2','3']);
console.log(JSON.stringify(allPermutations));
/*result:
["3","2","1"]
["3","2","1"]
["3","2","1"]
["3","2","1"]
["3","2","1"]
["3","2","1"]*/
What's wrong with this? Would love to understand. Thanks
Replace allPermutations.push(arr) with allPermutations.push(arr.slice()).
The problem is, you keep pushing the same array, then changing that array. When you push an array, you don't push a copy of it: you push a reference. There is only one array, and six references to it; when you read them out, they all read the same, because they are all the same array.
.slice() will give you a new array with the same elements; this way, you get six new arrays into your result, instead of six mentions of the same array.
From one of my earlier answers that is almost-but-not-quite a duplicate, a metaphor I like for this:
As a metaphor, imagine a theatre director in casting. He turns to an actor, says "You... you'll be Romeo.". Then he looks at the same actor, says "You... you'll be Mercutio. Here, Mercutio, take this sword. Romeo... who told you to get a sword?!?" completely failing to realise that, if Romeo and Mercutio are the same person, if one of them picks up a sword, the other does it too.
That's because arrays are objects, and objects are passed by value, but that value is a reference.
Then, your code keeps pushing the same arr reference to allPermutations. But the values in that reference are modified later.
Instead, you should push a copy of the array. You can copy it with .slice().
var allPermutations = [];
function swap(arr, index1, index2) {
var dummy = arr[index1];
arr[index1] = arr[index2];
arr[index2] = dummy;
return arr;
}
function generate(n, arr) {
if (n == 1) {
allPermutations.push(arr.slice());
} else {
for (var i = 0; i < n - 1; i++) {
generate(n - 1, arr);
if (n % 2 == 0) {
arr = swap(arr, i, n - 1);
} else {
arr = swap(arr, 0, n - 1);
}
}
generate(n - 1, arr);
}
}
generate(3, ['1', '2', '3']);
document.write(JSON.stringify(allPermutations));
Let's say that i got a variable which it contains the number 19. I want to make an array from it with the following numbers
var positions = [ "00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19" ];
How is this possible in javascript?
Something like :
var number = 19;
var arr = [];
for ( i = 0; i <= number ; i++ ) {
arr.push(i < 10 ? ("0" + i.toString()) : i.toString());
}
demo : http://jsfiddle.net/Kfnnr/1/
Alternatively:
var mynumber = 19,
myarr = String(Array(mynumber+1))
.split(',')
.map(function(el,i){return i<10 ? '0'+i : ''+i;});
For zeropadding you may want to use:
function padLeft(nr,base,chr){
base = base || 10;
chr = chr || '0';
var len = (String(base).length - String(nr).length)+1;
return len > 0? Array(len).join(chr)+nr : nr;
}
// usage
padLeft(1); //=> '01'
padLeft(1,100); //=> '001'
padLeft(1,10000,'-'); //=> '----1'
Update 2019: in es20xx String.prototype contains a native padStart method:
"1".padStart(2, "0"); //=> "01"
// ^ max length
// ^ fill string (or space if omitted)
essentially you want to pad 0's and the answers here will not suffice and scale when the number is changed.. Probably the better solution would be
function padZero(num, size) {
var s = num+"";
while (s.length < size) s = "0" + s;
return s;
}
Using this example finally solved my own ##iterator function interface issue;
Thanks a lot
var myArray = [];
function getInterval (start, step, end, ommit){
for (start; start <= end; start += step) {
myArray.push( start < 10 ? ("" + start.toString()) : start.toString());
}
}
getInterval(2, 2, 20, 20);
myArray; // __proto__: Array
// (10) ["2", "4", "6", "8", "10", "12", "14", "16", "18", "20"]
myArray[4]; // "10"