This question already has answers here:
Find the min/max element of an array in JavaScript
(58 answers)
Closed 1 year ago.
I have an below array with elements.
Array [
0,
0,
0,
0,
0,
0,
0,
4116.38,
4120.87,
0,
0,
0,
]
How can i filter all the "0" value and the maximum value from the array?
You don't, you just use const maxInYourArray = Math.max(...yourArray), relying on modern spread syntax to turn your array into distinct arguments, because the Math.max function can take an arbitrary number of values as function arguments and returns the maximum value amongst them.
The same applies to Math.min, but that will obviously give you 0, so if you want to ignore all those zeroes, filter them out first: const minInYourArray = Math.min(...yourArray.filter(v => v!==0))
Related
This question already has answers here:
How to sort an array of integers correctly
(32 answers)
Sort number javascript array
(2 answers)
Closed 4 months ago.
If array A = [-1, -3, -2, 0];
if I try to sort it
like A.sort()
console.log(A)
return is [-1, -2, -3, 0] instead of [-3, -2, -1, 0]
The Array.prototype.sort accepts an optional callback function (a compare function) that you use to sort the array based on your preference.
In your example above, you didn't specify a compare function thus sort will default to:
sorting the elements of an array in place and returns the reference to the same array, now sorted. The default sort order is ascending, built upon converting the elements into strings, then comparing their sequences of UTF-16 code units values. Source: MDN
From the result sample you included, it seems you want to sort those numbers in an ascending order (smaller to bigger). To do so, you should pass a compare function to the sort method that describes that sorting logic you'd want to have.
Here's a live demo:
const myArray = [-1, -3, -2, 0];
/** Please check the linked docs page for more details */
console.log(myArray.sort((a, b) => a < b ? -1 : 1)); // or simply: "(a, b) => a - b)"
The above demo should print: [-3, -2, -1, 0].
You can do this:
A.sort((a, b) => a-b);
This question already has answers here:
Array.prototype.fill() different from fill as I go [duplicate]
(1 answer)
Unexpected behavior using Array Map on an Array Initialized with Array Fill [duplicate]
(1 answer)
Closed 2 years ago.
Playing around with different ways of instantiating Arrays with Javascript and I noticed some interesting behavior:
matrix = Array(3).fill(Array(3).fill(0))
Creates an NxN matrix of 0 values
[
[0,0,0],
[0,0,0],
[0,0,0]
]
I then tried changing the first row of the matrix to be all 1's:
matrix[0].fill(1)
Which for some reason turned ALL values in the matrix to 1's:
[
[1,1,1],
[1,1,1],
[1,1,1]
]
This behavior doesn't make sense to me. Shouldn't only the first row be affected by the final call to Array.fill? What's going on here?
Your code is equivalent to
let row = [0,0,0]
let matrix = [row, row, row];
row.fill(1);
because .fill(Array(3).fill(0)) calls Array(3).fill(0) once to get the fill value - if the fill argument were a callback, then it would call it for each item in matrix - but the fill argument is a value
In javascript, arrays are said to be a reference
var a = [1,2,3], b=a;
b[0] = 4
will result in both a and b referencing an array with values [4,2,3]
so, since each row is the same array, your result is as you've seen
try this instead
const matrix = Array.from({length:3}, () => Array(3).fill(0))
matrix[0].fill(1);
console.log(matrix);
The above is equivalent to
const matrix = [Array(3).fill(0), Array(3).fill(0), Array(3).fill(0)];
matrix[0].fill(1);
Now each entry in matrix is a different Array, not the same one each time
This question already has answers here:
How to add a new object (key-value pair) to an array in javascript?
(5 answers)
Closed 3 years ago.
I want to add more elements dynamically to an array that has a named structure, I have (this works):
var v = [{
x: 0,
y: 0
}];
It initializes the structure with 1 element with 2 values, but, I want to add more elements later in the page, something like:
v.x.push(2); // something like this would insert a new element and give value of 2 to x of the new element.
Can anyone help me with this, using pure JavaScript? Thanks.
You can use the JavaScript Array.prototype.push method, e.g.
let v = [{
x: 0,
y: 0
}];
v.push({
x: 2
});
console.log(v);
Was playing around with some code to create an array of 0's and found that for only one value NaN was returned instead of 0. I get this in Chrome, Node, and Firefox.
What's causing the second value to be NaN?
var arr = new Array(32).join(0).split('').map(parseInt)
// prints [0, NaN, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
console.dir(arr)
That's because the function passed to map will be called with three arguments:
The current array item
The index of that item
The whole array
In this case, that function is parseInt, which only uses two arguments:
The string to be parsed
The radix used to parse the string
Additional arguments will be ignored.
Therefore, for the 2nd item in the array (i.e. index 1), the call will be
parseInt("0", 1, ignoredArray)
When the radix is 1, NaN is returned:
Let R = ToInt32(radix).
If R ≠ 0, then
If R < 2 or R > 36, then return NaN.
Also note that if you used a bigger number like new Array(99), you would have seen NaNs starting at index 37.
The .map() function passes three arguments to the callback of which two are used by parseInt(): the value, and the index (the third is the array itself). When the index is 1, any string of digits will be an invalid value. The parseInt() function ignores the second argument when it's 0.
To elaborate: for the first element, parseInt() is called like this:
parseInt("0", 0)
because the array value is zero and the index is zero. On the second call, it's this:
parseInt("0", 1)
and that returns NaN.
Note that if you're not too picky about the results being all integers, you can do what you're trying to do with the Number constructor:
var arr = new Array(32).join(0).split('').map(Number);
In ES2015 (the newest ratified standard for JavaScript, which if we are all very good will be fully implemented in all browsers as our Christmas present) you can use the .fill() function:
var arr = new Array(31).fill(0);
The mapping passes three arguments to its function:
the element;
the index of that element within the array; and
the array itself.
The parseInt function will look at the first two of those, treating the first correctly as the string but treating the second as the base to use. When the base is neither zero nor in the inclusive range 2..36, it returns NaN (1). If you had an array with forty elements, you'd also see a bunch of NaN values at the end:
0, NaN, 0, 0, 0, ... 0, 0, 0, NaN, NaN
You'd also get some pretty strange results if the number strings were anything other than zero, since the array index would dictate what base was used to interpret it.
To actually fix this, you can just provide a function that will translate what map gives you to what parseInt expects (a map map, I guess you could call it):
function myParseInt(s,r,a) { return parseInt(s,10); }
var arr = new Array(32).join(0).split('').map(myParseInt)
alert(arr)
You might also want to have a look at the way you're creating this array, it will actually end up as an array of size 31 rather than 32. If you just want an array of '0' characters, you can just use:
var arr = new Array(32).fill('0')
assuming you have a browser that supports ECMAScript 2015, which is Safari, Firefox and Chrome-desktop as of the time of this answer.
(1) A base of zero is the default case for handling things like hex prefixes.
A base of one makes no sense in a purely positional system (where each digit is multiplied by a power of the base and accumulated) since the only allowed digit there would be 0, so each place value would be that zero multiplied by 1n. In other words, the only number possible in a base-one system would be zero.
Bases from 2 to 36 are therefore more sensible.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I want return the difference between 2 values how to do that?
0.0.0.1.0 and 0.0.0.1.12
so the difference between these two values is 12
so how to calculate that I tried with Math.abs() but it is fine with single digits.
Assuming that they are strings (since you can't have more than 1 full stop in a valid JS number), you could split it by . character and calculate the difference of individual components:
function numStringDiff(a, b) {
// split them on dot characters
const aParts = a.split('.');
const bParts = b.split('.');
// loop using longest array length as a container for mapped results
return Array(Math.max(aParts.length, bParts.length)).fill(undefined).map((_, i) => {
const i1 = parseInt(aParts[i] || 0); // fetch aParts[i] or default to 0
const i2 = parseInt(bParts[i] || 0); // fetch bParts[i] or default to 0
// return compared value after defaulting the values.
return i2 - i1;
});
}
console.log(numStringDiff('0.0.0.1.0', '0.0.0.1.12'));
The problem here is that, as you stated in the comments, they can be of different length. To make it work in this scenario, we must iterate an amount of times equal to the length of the longest array and ensure that any missing items in the shorter one are defaulted to some non-breaking value like 0 so that we can safely subtract every digit present in the longest list with something or 0.
Note that 0 is a value I only used to ensure you can calculate a difference between different-length arrays, choose any (numeric or float) value that fits your needs.
If in this case the second argument has less dots than the first, negative difference will be returned, otherwise if first is longer than last, positive difference will be returned.
Some examples:
numStringDiff('1.1.1', '1.1') // => [0, 0, -1]
numStringDiff('1.1', '1.1.1') // => [0, 0, 1]
numStringDiff('1.1.1', '1.1.1') // => [0, 0, 0]
For the absolute distance between two values, one can simply .map over this array:
numStringDiff('1.1.1', '1.1').map(num => Math.abs(num));
// OR, using short form:
numStringDiff('1.1.1', '1.1').map(Math.abs);
And finally, should you need the result as a string, simply .join it back together with '.':
numStringDiff('1.1.1', '1.1').map(Math.abs).join('.');
Do know what you are trying to achieve though. If you're trying to manually bisect version numbers (like semver versions) I'd recommend against it since there will always be scenario's uncovered by this function such as pre-releases that wouldn't include only digits but rather 0.0.0-pre-foo-version or something. Since I don't know what it is you're trying to do exactly I'll leave that a responsibility for you to figure out :)