Reputation: 189
i am very new to Javascript and I struggle to find a solution.
I got an dynamically changing array called pat
. The elements of the array have coordinates x and y.
So now, i want to use a loop to store all x values of all elements into a new array called newArray
. And then after filled newArray
, i wish to get the maximum value out of it. The problem is, that i currently struggle to use the push
function in the right way. My code is below. Hope, someone can help. Thank you guys!
for ( i = 0; i < pat.length; i++ ) {
console.log(pat[i].x);
var newArray = pat.push[i];
console.log(newArray);
};
Upvotes: 0
Views: 58
Reputation: 2678
You shoud decrate the array outside the for loop, otherwise it will be re-declarate on each iteration. You can declarate the Array with the array literal syntax var arrayName = [];
. To add elements to the array you should use arrayName.
push(value)
method . To find the biggest number in the array we have to use Math
this is built-in object that has properties and methods for mathematical constants and functions.
We need only max
method from those object, which takes numbers as arguments, from which it returns the biggest one Math.max(a, b, c, d ...)
while it takes only number we can't pass Array
as an argument to it, to do so we can use the apply
method which comes from Function.prototype.apply() it calls a function with a given this value, and arguments provided as an array (or an array-like object).
That's how we can put the array as an arguments to the Math.max.apply(thisArg, [argumentsAsArray]);
or Math.max.apply(null, newArray);
in your case.
var newArray = []; // create an empty array outside the for loop
for ( i = 0; i < pat.length; i++ ){
newArray.push(pat[i].x); // add new element to the array
}
console.log(newArray);
var max = Math.max.apply(null, newArray); // take biggest number from the array
console.log(max);
Upvotes: 0
Reputation: 7285
Use push
like that:
var newArray = []; // create an empty array
for (var i = 0; i < pat.length; i++) {
newArray.push(pat[i].x); // push the x value of the current element to the array
};
var max = Math.max.apply(null, newArray); // calculate the maximum of all x values
A more functional approach using map
would be:
var newArray = pat.map(obj => obj.x);
var max = Math.max.apply(null, newArray);
PS: Are you sure you want to call the array newArray
?
Edit: my solution to calculate the maximum works like this: Math.max
returns the highest value of all of its arguments. apply
calls Math.max
with the array's elements as arguments.
Upvotes: 1