Just wondering, what is the most efficient way to divide an array by a scalar? I can clearly loop over it, but efficiency is paramount in my case.
Common trivial way:
var array_2 = []
var array_1 = [original_data
var divisor = my_scalar
for(var i = 0, length = array.length; i < length; i++){
array_2.push(array[i]/divisor)
}
Any trick I can use (or a new approach altogether)?
Just wondering, what is the most efficient way to divide an array by a scalar? I can clearly loop over it, but efficiency is paramount in my case.
Common trivial way:
var array_2 = []
var array_1 = [original_data
var divisor = my_scalar
for(var i = 0, length = array.length; i < length; i++){
array_2.push(array[i]/divisor)
}
Any trick I can use (or a new approach altogether)?
Share Improve this question edited Jun 28, 2022 at 19:47 SuperStormer 5,4075 gold badges28 silver badges39 bronze badges asked Mar 3, 2017 at 16:55 Asher11Asher11 1,3253 gold badges16 silver badges32 bronze badges 11-
2
var array_2 = array_1.map(i => i / divisor);
– tymeJV Commented Mar 3, 2017 at 16:56 - cool trying it right away – Asher11 Commented Mar 3, 2017 at 16:57
-
@tymeJV: What makes you think a bunch of function calls will be more efficient than a
for
loop? (The difference in efficiency is extraordinarily unlikely to matter, mind...) – T.J. Crowder Commented Mar 3, 2017 at 16:57 -
2
Note that your mon trivial way could be more efficient (depending on which JavaScript engine you're talking about):
array_2[i] = array[i] / divisor
(notpush
). – T.J. Crowder Commented Mar 3, 2017 at 16:58 -
1
This answer on SIMD mathematics describes a possibly more efficient method but it seems to not be widely supported. Other than that, all the solutions provided, whether using
map
or just a loop will be generally the same in efficiency. – Justin Hellreich Commented Mar 3, 2017 at 17:04
3 Answers
Reset to default 6You've said you want the most efficient way. Fairly sure what you're doing is close, but you want assignment rather than push
, and in at least some JavaScript engines (V8 for instance, in the Chromium browsers), if you tell the Array
constructor an initial length, they'll pre-allocate backing storage (even though the array starts with no elements in it):
var array_2 = Array(array.length);
for(var i = 0, length = array.length; i < length; i++){
array_2[i] = array[i] / divisor;
}
Having said that: The difference between that and map
is going to be very very very very very very small and it's an exceptionally rare use case where it would matter. Whereas map
is clear, simple, short...
You could use map
for that:
var newData = data.map(function(item) { return item/scalar } )
const numbers = [350,451,758,456,999];
const dividedNum = num => num/7;
const output1 = numbers.map(dividedNum);
console.log(output1)