Imagine I have the following array of objects:
const object = [
{Name: "A", Nr: "01"},
{Name: "B", Nr: "02"},
{Name: "C", Nr: "04"},
{Name: "D", Nr: "06"},
{Name: "E", Nr: "07"},
];
And I have the following function:
const findCurrentNumber = (obj) => {
let numbers = obj.map((a) => {
return parseInt(a["Nr"]);
});
numbers.sort((a, b) => a - b);
let current = numbers[numbers.length - 1];
for (let i = numbers.length - 1; i > 0; i--) {
if (numbers[i - 1] !== numbers[i] - 1) current = numbers[i - 1];
}
return current + 1;
};
I will get the value 3 as return. But I want to do the same just using array methods (map, sort, reduce etc). I was trying and I stopped here:
const obj = object.map(a => parseInt(a["Nr"])).sort((a, b) => a - b);
I don't know how to continue from the part I declared the current variable.
Is it possible? If so, how can I do it?
Thank you!
1 Answer 1
You could take an approach for How to write the code with less time complexity for finding the missing element in given array range? and take the numerical values of Nr.
function getMissing(array) {
var min = array[0],
max = array[0],
missing = new Set;
array.forEach(v => {
if (missing.delete(v)) return; // if value found for delete return
if (v < min) while (v < --min) missing.add(min); // add missing min values
if (v > max) while (v > ++max) missing.add(max); // add missing max values
});
return missing.values().next().value; // take the first missing value
}
const
data = [{ Name: "A", Nr: "01" }, { Name: "B", Nr: "02" }, { Name: "C", Nr: "04" }, { Name: "D", Nr: "06" }, { Name: "E", Nr: "07" }],
first = getMissing(data.map(({ Nr }) => +Nr));
console.log(first);
Classic approach. By checking an ordered array of numbers and get the one where the next value has a delta of more than one. Finally add one for the missing number.
const
data = [{ Name: "A", Nr: "01" }, { Name: "B", Nr: "02" }, { Name: "C", Nr: "04" }, { Name: "D", Nr: "06" }, { Name: "E", Nr: "07" }],
first = 1 + data
.map(({ Nr }) => +Nr)
.sort((a, b) => a - b)
.find((l, i, { [i + 1]: r = Number.MAX_VALUE }) => r >= l + 2);
console.log(first);
4 Comments
O(n*m) where n is the input size and m is the largest gap between the numbers. For example [1, 3] will only generate 2 but [0, 9001] will generate the entire range from 1 to 9000 because of the gap between the two elements.
1larger than the element following it.current, you're doing string concatenation. I'm still not sure what the point is.