JavaScript array map: callback vs arrow function [duplicate] - javascript

This question already has answers here:
Shortcut of calling a method without writing parameters in Javascript
(4 answers)
What is .map() doing in this situation?
(4 answers)
Closed 1 year ago.
I ran into an issue regarding array mapping functions in JS and cannot explain why this is happening, nor do I find any helpful search results with an explanation. Sorry if this was posted already somewhere.
Could anyone explain why the results differ?
const [ i, j ] = "1x2".split('x').map((value) => parseInt(value));
console.log(i);
console.log(j);
const [ i, j ] = "1x2".split('x').map(parseInt);
console.log(i);
console.log(j);
cheers

parseInt receives as second argument the radix:
radix Optional
An integer between 2 and 36 that represents the radix (the base in mathematical numeral systems) of the string. Be careful—this does not default to 10! If the radix value is not of the Number type it will be coerced to a Number.
So, when you do:
const [ i, j ] = "1x2".split('x').map(parseInt);
it is the same like:
const [ i, j ] = "1x2".split('x').map((value, index) => parseInt(value, index));
(the map callback is called with currentValue, currentIndex and arrayReference)
Hence, parseInt("2", 1) is NaN because 1 is not a valid radix value.

Related

Why is my for loop breaking earlier than expected?

I am trying to solve a problem on leetCode:
Given an unsorted integer array nums, return the smallest missing positive integer.
This is the code I came up with
var firstMissingPositive = function(nums) {
nums.sort();
let x = 1; //this is to compare the elements of nums
for (let num in nums) {
if (nums[num] <= 0) continue; //because anything less than 1 does not matter
else if (nums[num] != x) break; //if x is not present, x is the answer
else x++; // if x is present, x should increment and check for the next integer
}
return x;
};
This code works 106/173 testcases. It does not pass the following case, which looks very simple -
nums = [1,2,3,4,5,6,7,8,9,20];
The output I get is 3, whereas the expected output is 10.
I'm not looking for the right solution to the problem. I'm just curious why this seemingly simple test fails. I do not understand why my loop breaks at 3 when it passes 1 and 2. Please help!
Here's the root cause of your problem (mdn):
The sort() method sorts the elements of an array in place and returns
the sorted array. The default sort order is ascending, built upon
converting the elements into strings, then comparing their sequences
of UTF-16 code units values.
So what you get after sort is [1, 2, 20, 3, ...], as '20' string precedes '3' string. One possible way to fix this it to force sorting by numeric value:
nums.sort((a, b) => a - b);

Concatenating Numbers in javascript [duplicate]

This question already has answers here:
Javascript Concatenate Array to String
(2 answers)
Closed 2 years ago.
My goal is to make numbers into strings.
If my actual = concatenateNumbers(7);
expected = "7"
My code for this would be:
function concatenateNumbers(num1) {
return num1.toString();
}
However, if my actual has 2 or 3 more values, actual = concatenateNumbers(7, 9) or actual = (7, 9 ,1) => the expected is = "79" or "791"
Can anybody give me an idea or hint on how I should approach this?
Use The arguments object converted to a real Array, and use Array.prototype.join() with an empty String:
function concatenateNumbers() {
return [...arguments].join("");
}
var numbersArrays = [
[],
[7],
[7, 9],
[7, 9, 1]
];
numbersArrays.forEach(numbersArray=>{
console.log(numbersArray.join(", ") + " => " + concatenateNumbers(...numbersArray));
});
console.log("1, 2, 3 => "+concatenateNumbers(1, 2, 3));
numbersArrays is just a convenient way to use SO's code snippet, along with "["+numbersArray.join(", ")+"]" to show each numbersArrays's Array as an Array, plus the actual call to the actual function concatenateNumbers.
Edited to make function's arguments actually a list of Numbers using the Spread syntax (...), as pointed out by VLAZ.
It will actually concatenate anything, the best it can...

Manufacturing an array - why is it different? [duplicate]

This question already has answers here:
JavaScript "new Array(n)" and "Array.prototype.map" weirdness
(14 answers)
Closed 5 years ago.
consider I declare two variables like this (done within REPL, with node v7.7.2), which I expect to be arrays:
var x = Array(4)
var y = Array.from({length: 4})
then the following should work identically, but it doesn't:
x.map(Math.random)
[ , , , ]
y.map(Math.random)
[ 0.46597917021676816,
0.3348459056304458,
0.2913995519428412,
0.8683430009997699 ]
in looking, it seems x and y are both identical:
> typeof x
'object'
> typeof y
'object'
> Array.isArray(x)
true
> Array.isArray(y)
true
> x.length
4
> y.length
4
> typeof x[0]
'undefined'
> typeof y[0]
'undefined'
so why the difference?
Actually, it should not have the same results fot both cases. See the manual here about Array:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array
If the only argument passed to the Array constructor is an integer
between 0 and 232-1 (inclusive), this returns a new JavaScript array
with its length property set to that number (Note: this implies an
array of arrayLength empty slots, not slots with actual undefined
values). If the argument is any other number, a RangeError exception
is thrown.
And here about the Array.from() method
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/from
Check the following example on the page linked above:
// Generate a sequence of numbers
// Since the array is initialized with `undefined` on each position,
// the value of `v` below will be `undefined`
Array.from({length: 5}, (v, i) => i);
// [0, 1, 2, 3, 4]
For the first three outputs, Array#map works.
It is not called for missing elements of the array (that is, indexes that have never been set, which have been deleted or which have never been assigned a value).
The ECMA 262 standard to Array.from describes a construction with length for a new array (point 7 ff).
var x = Array(4),
y = Array.from({ length: 4 }),
arrayX = x.map(Math.random),
arrayY = y.map(Math.random),
z = Array.from({ length: 4 }, Math.random);
console.log(x);
console.log(y);
console.log(arrayX);
console.log(arrayY);
console.log(z);
The Array created with Array(4) is not iterated over with .map(), whereas the Array.from({ length: 4 }) is iterated over. A fuller explanation can be found at JavaScript "new Array(n)" and "Array.prototype.map" weirdness, you can test this with..
x.map((f,i) => console.log(i)) vs. y.map((f,i) => console.log(i))

Strange map behaviour [duplicate]

This question already has answers here:
Why does parseInt yield NaN with Array#map?
(8 answers)
Closed 6 years ago.
What is the difference between map(func) and map(function(x) { return func(x); })?
Consider this example:
const lines = '1\n2\n3';
const result = lines.split('\n').map(parseInt);
console.log(result )
This returns [1, NaN, NaN] which is not what I expected.
However:
const lines = '1\n2\n3';
const result = lines.split('\n').map(function(x){ return parseInt(x)});
console.log(result)
returns the expected: [1, 2, 3]. What is the difference between these two forms and why in the first example the result is not [1, 2, 3]?
parseInt has a second parameter (radix).
Basically you perform this
value index parseInt comment
----- ----- -------- -----------------------------------------------------
'1' 0 1 with radix 0, and value 1 parseInt assumes radix = 10
'2' 1 NaN because of the wrong value for the radix
'3' 2 NaN because of the wrong value for the radix
For converting to a number, you could use Number.
var lines = '1\n2\n3'
console.log(lines.split('\n').map(Number));
For getting integer values, you could use Math.floor as well.
var lines = '1\n2\n3'
console.log(lines.split('\n').map(Math.floor));
The difference is that .map passes to its function 3 parameters:
.map(element, index, array)
when the parseInt function accepts 2 arguments
parseInt(string, radix)
So, you pass index as a radix. That is why your result is wrong. If parseInt was accepting just one argument it would work.
Because the index from the map will be passed into the map function
let lines = '1\n2\n3'
let a = lines.split('\n').map(parseInt);
console.log(a)
// Your code above is expanded as below
a = lines.split('\n').map((x, i) => {
return parseInt(x, i)
})
console.log(a)
// To fix it, use this
lines.split('\n').map(x => parseInt(x));

javascript for loop counter coming out as string [duplicate]

This question already has answers here:
Why does javascript turn array indexes into strings when iterating?
(6 answers)
Is a JavaScript array index a string or an integer?
(5 answers)
Why is key a string in for ... in
(3 answers)
When iterating over values, why does typeof(value) return "string" when value is a number? JavaScript
(1 answer)
Closed 1 year ago.
I've simplified my program down to this, and it's still misbehaving:
var grid = [0, 1, 2, 3];
function moveUp(moveDir) {
for (var row in grid) {
console.log('row:');
console.log(row + 5);
}
}
It seems that row is a string instead of an integer, for example the output is
row:
05
row:
15
row:
25
row:
35
rather than 5, 6, 7, 8, which is what I want. Shouldn't the counter in the for loop be a string?
Quoting from MDN Docs of for..in,
for..in should not be used to iterate over an Array where index order
is important. Array indexes are just enumerable properties with
integer names and are otherwise identical to general Object
properties. There is no guarantee that for...in will return the
indexes in any particular order and it will return all enumerable
properties, including those with non–integer names and those that are
inherited.
Because the order of iteration is implementation dependent, iterating
over an array may not visit elements in a consistent order. Therefore
it is better to use a for loop with a numeric index (or Array.forEach
or the non-standard for...of loop) when iterating over arrays where
the order of access is important.
You are iterating an array with for..in. That is bad. When you iterate with for..in, what you get is the array indices in string format.
So on every iteration, '0' + 5 == '05', '1' + 5 == '15'... is getting printed
What you should be doing is,
for (var len = grid.length, i = 0; i < len; i += 1) {
console.log('row:');
console.log(grid[i] + 5);
}
For more information about why exactly array indices are returned in the iteration and other interesting stuff, please check this answer of mine
You should use a normal for loop rather than a for...in loop for arrays.
for (var row = 0, l = grid.length; row < l; row++) {
console.log('row:');
console.log(5 + row);
}
I think this is what your expected output should be.
Fiddle
Try with parseInt(..) method to force int value
console.log(parseInt(row,10) + 5);
second param 10 is to be parsed as decimal value.
See the answer here How do I add an integer value with javascript (jquery) to a value that's returning a string?

Categories