Reputation: 31
Working on exercises to build up my Javascript array skills.
Question is as follows: Write a function biggest_smallest that takes an array of numbers as an input, uses .forEach(), and returns an array containing the smallest number in the zeroth position and the largest number in the first position.
Instead of using forEach(), the only way I could think of doing this was as follows:
var array_of_nums = [7, 8, 120, 60, 10]
function biggest_smallest(array){
var new_array = []
for (var i = 0; i < array.length; i++){
if (array[i] === Math.min.apply(Math, array)){
new_array.unshift(array[i])
} else if (array[i] === Math.max.apply(Math, array)) { ? }
}
return new_array
}
I'm not able to figure out how to place the largest number in index 1 (let alone refactor it using a forEach() method) to solve this exercise complete. I am assuming my method of placing the smallest number in index 0 is correct.
Any help is much appreciated. Thanks.
Upvotes: 0
Views: 2016
Reputation: 31
var array_of_nums = [7, 8, 120, 60, 10]
function smallest_biggest(arr) {
var new_array = []
arr.forEach(function() {
new_array[0] = Math.min.apply(Math, arr)
new_array[1] = Math.max.apply(Math, arr)
})
return new_array
}
smallest_biggest(array_of_nums)
Upvotes: 0
Reputation: 36511
edit My mistake, the question requires forEach
iteration, so I suppose there is a need
There really is no need for iteration, you can just use Math.min
/Math.max
function biggest_smallest(array){
return [Math.min.apply(null, array), Math.max.apply(null, array)];
}
Upvotes: 1
Reputation: 55678
Assuming this is supposed to work more or less like d3.extent
I think the easiest option is just to iterate through with Math.min
and Math.max
checks:
function smallest_biggest(arr) {
// ditch if no input
if (!array.length) return [];
// start with comparable values
var extent = [Infinity, -Infinity];
arr.forEach(function(val) {
extent[0] = Math.min(extent[0], val);
extent[1] = Math.max(extent[1], val);
});
return extent;
}
Underscore's _.min
and _.max
functions used to skip the first check, with the incredibly annoying result that _.min([]) === Infinity
.
Upvotes: 3
Reputation: 626
I'd say first you need to find two variables: a (minimum value in the array) and b (the maximum). Then, outside the loop (that you can implement using foreach or the regular syntax) you just push the two values to the resulting array:
new_array.push(a);
new_array.push(b);
return new_array;
Upvotes: 0