Reputation: 458
Good afternoon, I was given a task to create to a function which returns the multiply of three highest numbers in array.
The only way of how I manage to do this.
var stringArray = new Array('8','-1','2','2','0','14');
// Converting strings to numbers
var intArray = stringArray.map(Number);
// Sorting out and multiplying result
var first = intArray.sort(function(a,b){return b-a})[0];
var second = intArray.sort(function(a,b){return b-a})[1];
var third = intArray.sort(function(a,b){return b-a})[2];
console.log(first * second * third); // 224 is result
Any way of how I can do it in a function?
Upvotes: 0
Views: 219
Reputation: 1245
let stringArray = new Array('8','-1','2','2','0','14');
// Converting strings to numbers
let intArray = stringArray.map(Number);
const result = intArray.sort((a, b) => b - a).slice(0,3).reduce((acc,cur) => acc*cur);
console.log(result);
Upvotes: 0
Reputation: 4180
You can do it like this:
let result = stringArray.map(Number).sort((a,b)=>b-a).slice(0,3).reduce((acc,a)=> acc*a,1)
Upvotes: 3