Reputation: 86
I have an array produced by a range(i, (i + j)) function which uses two counters i and j. The range function works well to produce an array of the type [3, 4, 5, 6]
Once this array is produced, I would like to point to object 3, 4, 5, and 6 in another array called y.
Within each of the objects pointed to, the key I want the value of is called 'weight'.
I want to use Math.max to return the one with the largest weight.
Can someone please help me, I am new to JavaScript and am not very good at this.
Thank you.
I tried the following code, but it gives an error
var m = Math.min( ( y[range(i, (i + j))].weight )
)
console.log(m)
The error given is "cannot read property 'weight' of undefined". It's because the range function returns an array of the numbers I want to test so it's trying to process it as:
var m = Math.min( ( y[[3, 4, 5, 6]].weight )
)
console.log(m)
instead of the following, which I would like to see:
var m = Math.min( ( y[3].weight ), ( y[4].weight ), ( y[5].weight ), ( y[6].weight )
)
console.log(m)
Would using reduce() be appropriate in helping the code sequentially run each number in the returned array from range function, and if so, how could reduce() be implemented?
Thanks so much, I really appreciate it.
Upvotes: 1
Views: 205
Reputation: 6641
You don't need to use range(i, i+j)
function if you just want to use it to access the y
array.
You can use JavaScript's slice() method to create a new array from y
array between indices i
and i+j+1
.
var y2 = y.slice(i, i+j+1);
Now, you can use map() method to create a new array with just weight
properties from each object of y2
array.
var weights = y2.map(obj => obj.weight);
To find the minimum of these weights, you can use JavaScript's Math.min() function. Spread syntax can be used to pass the weights array as argument to Math.min() function.
var min = Math.min(...weights);
Demo:
var y = [
{"weight": 100, "a": 1, "b": 2},
{"weight": 200, "a": 1, "b": 2},
{"weight": 300, "a": 1, "b": 2},
{"weight": 400, "a": 1, "b": 2},
{"weight": 500, "a": 1, "b": 2}
];
var i = 1, j= 2; // Values used in your range() function.
var y2 = y.slice(i, i+j+1);
var weights = y2.map(obj => obj.weight);
console.log("All weights: " + weights);
var min = Math.min(...weights);
console.log("Minimum weight: " + min);
Upvotes: 0
Reputation: 403
Use array.map() instead coupled with the spread syntax, like so:
const min = Math.min( ...( range(i, i+j).map(i => y[i].weight) ) );
The map operator will create a new array with the result of the callback function, and the spread syntax (those ...
) will 'spread' the array values as if they were arguments.
Upvotes: 0