Here is a recursive function, excluding the sorting which should only happen once:
var pointlist = [];
var pointCount = 666;
var generate = function(t, n) {
for (count = 0; count < n; count++) {
var point = {
x: Math.floor(Math.random() * 1000),
y: Math.floor(Math.random() * 1000)
};
t.push(point);
}
}
generate(pointlist, pointCount);
var divide = function(a) {
a.sort(function(a, b) {
return a.x - b.x
});
function recurseDivide(a) {
if (a.length <= 3) return [a];
var b = a.splice(Math.round(a.length / 2), a.length);
return recurseDivide(a).concat(recurseDivide(b));
}
return recurseDivide(a);
};
var divisions = divide(pointlist);
console.log(divisions.length + " arrays");
console.log(divisions[0].length + " first length");
console.log(divisions[1].length + " second length");</script>
Be aware that after the call to divide, the variable pointlist will have mutated. If you want to avoid this, make the call like this:
var divisions = divide(pointlist.slice());
Answer from trincot on Stack OverflowHere is a recursive function, excluding the sorting which should only happen once:
var pointlist = [];
var pointCount = 666;
var generate = function(t, n) {
for (count = 0; count < n; count++) {
var point = {
x: Math.floor(Math.random() * 1000),
y: Math.floor(Math.random() * 1000)
};
t.push(point);
}
}
generate(pointlist, pointCount);
var divide = function(a) {
a.sort(function(a, b) {
return a.x - b.x
});
function recurseDivide(a) {
if (a.length <= 3) return [a];
var b = a.splice(Math.round(a.length / 2), a.length);
return recurseDivide(a).concat(recurseDivide(b));
}
return recurseDivide(a);
};
var divisions = divide(pointlist);
console.log(divisions.length + " arrays");
console.log(divisions[0].length + " first length");
console.log(divisions[1].length + " second length");</script>
Be aware that after the call to divide, the variable pointlist will have mutated. If you want to avoid this, make the call like this:
var divisions = divide(pointlist.slice());
Not recursive but with the help of a useless Array method called Array.prototype.bisect() may be you can do something as follows;
Array.prototype.bisect = function(){
var atIndex = Math.round(this.length/2);
return [this.slice(0,atIndex),this.slice(atIndex)];
};
var arr = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19],
brr = [];
function breakUp(arr){
while (arr[0].length > 3) arr = [].concat(...arr.map(a => a.length > 3 && a.bisect()));
return arr;
}
brr = breakUp([arr]);
console.log(JSON.stringify(brr));
You'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 } )
Videos
This should do it for you:
var divisor = 16;
var array = [{"x":0,"y":16},{"x":16,"y":32},{"x":32,"y":48}];
for(var i = 0, length = array.length; i < length; i++){
array[i] = {'x':array[i].x/divisor,'y':array[i].y/divisor};
}
In case you are likely to extend the objects in the future, you might want to do it like this, instead:
for(var i = 0, length = array.length; i < length; i++){
array[i].x /= divisor; // `a[i].x /= d` is shorthand for `a[i].x = a[i].x / d`
array[i].y /= divisor;
}
This has the advantage that it doesn't overwrite array[i], saving possible other properties.
Another solution, using map and a callback:
var divisor = 16;
var array = [{"x":0,"y":16},{"x":16,"y":32},{"x":32,"y":48}];
array = array.map(function(v){
return {x: v.x / divisor, y: v.y / divisor};
});
You could reduce the array and push a new array to the result if you have the wanted value. Then push all values to the last array in the result set.
var array = ["a", "b", "c", "d", "a", "b", "a", "b", "a"],
result = array.reduce((r, v, i) => {
if (!i || v === 'a') r.push([]);
r[r.length - 1].push(v);
return r;
}, []);
console.log(result);
You can convert array to string and then use match() and RegExp. Then then use map() to get array of arrays
let arr = ["a","b","c","d","a","b","a","b","a"]
let res = arr.join('').match((/a[^a]+/g)).map(x => [...x]);
console.log(res)
If your intent is to produce e.g. ((a / b) / c) given the input array [a, b, c] then you should omit the "initial value" field because there is no "identity" value for the division operator in the way that "0" is the identity to addition and "1" is the identity for multiplication.
function divideArray(array) {
return array.reduce(function(total, number) {
return total / number;
});
}
This will reduce (pun not really intended) to just returning the original value if only a single value is supplied since by definition the reduce function does not call its callback if only a single value is supplied.
With appropriate separation of concerns and simplification of functions to their smallest testable units, your entire code could reduce to:
function _getFieldNumber(product, field) {
return _extractNumber(helper.getPropertyValue(product, field.trim()));
}
function _getFieldNumbers(product, fields) {
return fields.map(_getFieldNumber.bind(this, product));
}
function _multipleFields(product, fields) {
return _getFieldNumbers(product, fields).reduce(multiply, 1);
}
function _divideFields(product, fields) {
return _getFieldNumbers(product, fields).reduce(divide);
}
function multiply(a, b) { return a * b; }
function divide(a, b) { return a / b; }
As you are using similar functions for multiplication and division, you should try to make them generic.
One way is to get first field and extract number from it and use this as initialValue for .reduce. This way you can keep structure same.
function _operateFields(product, fields, operand) {
var initial = getNumericValue(product, fields[0])
var total = fields.slice(1).reduce(function(total, field) {
var num = getNumericValue(product, field);
return (operand === "/") ? total / num: total * num
}, initial);
return total;
};
function getNumericValue(product, field) {
return _extractNumber(helper.getPropertyValue(product, field.trim()));
}
var answer = Math.floor(x)
I sincerely hope this will help future searchers when googling for this common question.
var x = parseInt(455/10);
The parseInt() function parses a string and returns an integer.
The radix parameter is used to specify which numeral system to be used, for example, a radix of 16 (hexadecimal) indicates that the number in the string should be parsed from a hexadecimal number to a decimal number.
If the radix parameter is omitted, JavaScript assumes the following:
If the string begins with "0x", the radix is 16 (hexadecimal) If the string begins with "0", the radix is 8 (octal). This feature is deprecated If the string begins with any other value, the radix is 10 (decimal)
If you have ES5 support, this may be a good option:
var result = A.map(function(n, i) { return n / B[i]; });
Where n in callback represents the iterated number in A and i is the index of n in A.
Assuming the two arrays are always the same length:
var C = [];
for (var i = 0; i < A.length; i++) {
C.push(A[i] / B[i]);
}