I'm having trouble solving this problem:
I have an array of objects:
tableList = [
{table_number: 1},
{table_number: 11},
{table_number: 31}
]
I'm trying to generate a bracket list in steps of 10 up to the largest 'table_number'.
I'm using a sequence generator function for this:
// Sequence generator function (commonly referred to as "range", e.g. Clojure, PHP etc)
const range = (start, stop, step) => Array.from({ length: (stop - start) / step + 1}, (_, i) => start + (i * step));
I'm using Math.max and iterate through the array to find the biggest 'table_number':
// Search for biggest table number
var max = Math.max.apply(Math, data.map(o => o.table_number));
I then generate the bracket array with the sequencing function:
// Generate brackets up until biggest table number
var brackets = range(0, max, 10);
This gives me a bracket array of [0, 10, 20, 30].
Now the question is, how do I evaluate the array of objects to remove the empty bracket step (20) that will not contain any 'table_number'?
Or should I be generating the bracket array differently?
I would really appreciate any help for this, thanks!
In case anyone stumbles on this, I have found this to be my solution.
const brackets = [...new Set(data.map(item => item.table_number - (item.table_number % 10)))]
I visit each element in the object and then subtract from it's remainder to get the numbers in steps of 10.
I then create a Set object from the outcome, effectively removing all duplicates.
Or should I be generating the bracket array differently?
If you're just after an array like [0,10,30] you can follow a different path:
tableList = [
{table_number: 1},
{table_number: 11},
{table_number: 31}
]
const tmpObj = tableList.reduce( (acc,cur) => {
acc[ Math.floor(cur.table_number/10)*10 ] = true;
return acc;
} , {})
const brackets = Object.keys(tmpObj).map((x) => parseInt(x));
console.log(brackets);
But this is taking advantage of how easy is "in steps of 10"