1

I have the following array:

const arr = [
  [5, 0.2],
  [7, 0.6],
  [8, 0.3],
  [10, 0.4]
];

console.log(arr)

I need to ensure that the first element of the array is a sequence from 5 to 10:

[5, 6, 7, 8, 9, 10]

In the above example, these numbers within the sequence are missing:

[6, 9]

If they are missing, I need to include them with zeros:

const expectedResult = [
  [5, 0.2],
  [6, 0],
  [7, 0.6],
  [8, 0.3],
  [9, 0],
  [10, 0.4]
];

console.log(expectedResult)

Any ideas on how to achieve this?

2
  • Is the sequence range known? Commented Apr 21, 2021 at 8:52
  • yes, from 5 to 10 Commented Apr 21, 2021 at 8:58

1 Answer 1

4

You could map the missing parts with a closure over the actual index of the given array.

const
    array = [[5, 0.2], [7, 0.6], [8, 0.3], [10, 0.4]],
    result = Array.from(
        { length: 6 },
        (i => (_, j) => array[i]?.[0] === j + 5 ? array[i++] : [j + 5, 0])(0)
    );

console.log(result);

Sign up to request clarification or add additional context in comments.

1 Comment

@thgaskell, no, because found, it should increment to get the next element in the next loop.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.