Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

172
Views
All elements after first occurrence of closest element or first nearest by element

How would you write a function in JS for the following: Get the subarray of all elements:

  • after and including the first occurrence of the searched element
  • or after and including the first number greater than the searched element.

These tests should pass:

expect(elementsStartingFrom([1, 3, 5, 7, 9, 11], 1)).toEqual([1, 3, 5, 7, 9, 11]);
expect(elementsStartingFrom([1, 3, 5, 7, 9, 11], 2)).toEqual([3, 5, 7, 9, 11]);
expect(elementsStartingFrom([1, 3, 5, 7, 9, 11], 3)).toEqual([3, 5, 7, 9, 11]);
expect(elementsStartingFrom([1, 3, 5, 1, 4, 5], 2)).toEqual([3, 5, 1, 4, 5]);
about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

First, use indexOf to see if the item is in the list. If not, filter out anything less than, sort that to get next biggest, then use indexOf to find the index of that. Finally, use slice to get the part of the array:

const elementsStartingFrom = (haystack, needle) => {
    let idx = haystack.indexOf(needle);
    if (-1 == idx) {
        const tmp = haystack.filter(i => i > needle).sort((a, b) => a - b).at(0);
        idx = haystack.indexOf(tmp);
    }
    if (idx == -1) return null;
    else return haystack.slice(idx);
};

You could remove the first call to indexOf and get the same result by changing the < to <=:

const elementsStartingFrom = (haystack, needle) => {
    const tmp = haystack.filter(i => i >= needle).sort((a, b) => a - b).at(0);
    const idx = haystack.indexOf(tmp);
    return (idx == -1) ? null : haystack.slice(idx);
};
about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!