Published
Edited
Apr 24, 2019
Insert cell
Insert cell
Insert cell
function missing(arr) {
// First find the max value of the array, that way we can now that we start from 1 and end on the max value
// In the example [4, 1, 3, 6] the max value is 6 so we go from 1 to 6.
const max = Math.max(...arr);
// We iterate the given array with reduce to return only the missing elements
return arr.reduce((missing, current, i, s) => {

// If the current element is 1 or the same value as max, we ignore it and the return the missing
if(current !== 1 && current !== max) {
// We are gonna store the previous value and the next value of the current element in a and b
let [a, b] = [[], []]
// We calculate the previous and next value and check if is in the array
// Example: if 4 is our current element the previous is 3 and the next is 5,
// So we check if 3 and 5 are in the array
if(!s.includes(current - 1)) a = current - 1;
if(!s.includes(current + 1)) b = current + 1;
// Then return the previus missing elemets with the newest elements that we didnt find
return [...missing, ...[].concat(a, b)]
}
return missing;

}, []);

}
Insert cell
missing([4, 1, 6, 3])
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more