JavaScript Challenge - Find Xth Number In Order

This community-built FAQ covers the “Find Xth Number In Order” code challenge in JavaScript. You can find that challenge here, or pick any challenge you like from our list.

Top Discussions on the JavaScript challenge Find Xth Number In Order

There are currently no frequently asked questions or top answers associated with this challenge – that’s where you come in! You can contribute to this section by offering your own questions, answers, or clarifications on this challenge. Ask a question or post a solution by clicking reply (reply) below.

If you’ve had an “aha” moment about the concepts, formatting, syntax, or anything else with this challenge, consider sharing those insights! Teaching others and answering their questions is one of the best ways to learn and stay sharp.

Join the Discussion. Help a fellow learner on their journey.

Ask or answer a question about this exercise by clicking reply (reply) below!
You can also find further discussion and get answers to your questions over in Language Help.

Agree with a comment or answer? Like (like) to up-vote the contribution!

Need broader help or resources? Head to Language Help and Tips and Resources. If you are wanting feedback or inspiration for a project, check out Projects.

Looking for motivation to keep learning? Join our wider discussions in Community

Learn more about how to use this guide.

Found a bug? Report it online, or post in Bug Reporting

Have a question about your account or billing? Reach out to our customer support team!

None of the above? Find out where to ask other questions here!

A post was merged into an existing topic: Python Challenge - Find Xth Number In Order

It would only accept my version when I did:
when there is no Xth number, return 0 (instead of undefined).

Minimal version using .sort()
although I had to provide a comparison function to it for it to work properly.

const compare = (a, b) => {
  if (a < b) { return -1; }
  else if (a > b) { return 1; }
  else { return 0; }
}

const getX = (x, nums) => { 
  const result = Array.from(nums).sort(compare)[x - 1];
  return result ? result : 0;
}
1 Like

Here’s another version where I made an iterator (using a generator function) and did a simple sorting algorithm in it (not in-place).
The algorithm I used is: find min, insert it in new array, find min of remaining stuff, insert it, etc. 0(n2 )

my code (long)

I split the tasks into 3 functions, instead of writing more loops inside loops.

function min(nums, bools, changeMinToFalse) {
  // finds minimum only for positions where bools has true
  let minimum = undefined;
  let indexOfMin = undefined;
  const length = nums.length;
  for (let i = 0; i < length; i++) {
    if ((bools == undefined) || bools[i]) {
      if ((minimum == undefined) || (nums[i] < minimum)) {
        minimum = nums[i];
        indexOfMin = i;
      }
    }
  }
  if (changeMinToFalse && !(indexOfMin == undefined)) {
    bools[indexOfMin] = false;
  }
  return minimum;
}

function* inOrder(arr) {
  // generator function to iterate from least to greatest
  const length = arr.length;
  const notUsedYet = new Array(length);
  notUsedYet.fill(true);
  for (let i = 0; i < length; i++) {
    yield min(arr, notUsedYet, true);
  }
}

function getX(x, nums) {
  const length = nums.length;
  if (x < 0) { x = length + x; }
  const iterator = inOrder(nums);
  for (let i = 1; i <= length; i++) {
    if (i == x) {
      return iterator.next().value;
    }
    else {
      iterator.next();
    }
  }
  return 0;
  /* had to return 0 instead of undefined 
     because of answer checker */
}

Here is my example code. I needed to add the sort function check manually for it to work. !

 function getX(x, nums) {

// Write your code here

   const sorty = (a, b) => {
    return a - b; 

    }

    let arr = nums.sort(sorty);
     let answer = 0; 

     arr.forEach((value, iterator) => {
     if(iterator === x - 1){
       answer = value; 
      }
    })

  return answer; 
  }

  console.log(getX(4, [5, 10, -3, -3, 7, 9]));

  // Leave this so we can test your code:
  module.exports = getX;

const getX = (x, nums) => x < 1 || x > nums.length ? 0 : nums.sort((a,b) => a-b)[x-1]

1 Like
function getX(x, nums) {


 nums.sort((a, b) => a - b);
 
  if(x < 1 || x > nums.length){
   return 0;
 }

return nums[x - 1];
  
}


module.exports = getX;

Thank you! I returned “Error” instead of 0 for broken inputs and failed testcases and I couldn’t find out why. The instructions missing some points. As someone who learned C, returning 0 when the function is broken is very painful.

1 Like

Used BubbleSort to clear this challenge.
Very doable after the lessons on BubbleSort.

Validating that x is in the array provided the final two checkmarks.
Cheerio!

function getX(x, nums) { //step 1 : sort the list const sort = (array) =>{ let swapping = true; while(swapping){ swapping = false; for(let i = 0; i < array.length -1;i++){ if(array[i] > array[i+1]){ swap(array, i, i+1) swapping = true; } } } return array; } const swap = (array, indexOne, indexTwo) => { let temp = array[indexOne]; array[indexOne] = array[indexTwo]; array[indexTwo] = temp; } //call the sort function to sort the list; sort(nums); if (x > nums.length || x < 1){ return 0; } return nums[x-1]; } console.log(getX(2, [5, 10, -3, -3, 7, 9])); // Leave this so we can test your code: module.exports = getX;
1 Like

Your solution with BubbleSort is radically faster than other
Test: x=500, array with 1000 random integer from -50 to 50 (warming up, 1000 calls of 20 passes)

  1. 0.022 Array.sort
  2. 1.536 janbazant1107978602’s solution with generator
  3. 0.002 Your solution. Wow!
2 Likes
function getX(x, nums) {
  if (!x || x > nums.length) 
    return ''
  const arr = nums.sort((a, b) => a - b)
  return arr[x-1]
}

module.exports = getX;

My idea was not to sort all list because we need only x minimums from the nums array to get the correct number from the list, so we will sort all list only in the worst case when x=nums.length. In the worst case, we got time complexity O(N^2) same as bubble sort, but in other cases, we got an advantage because we don’t need to sort all list.
The outer loop will run x times to find x minimums, each time you find a minimum you push it to the sorted array, record the index of this minimum and remove this minimum from the nums length decrease n-1, and all repeats, we search next minimum until sorted array length become x. I hope my logic didn’t go wrong and there is still some advantage. :slightly_smiling_face:

function getX(x, nums) { // Write your code here const sortedArray = []; let min = nums[0]; let index = 0; if (x > 0 && x <= nums.length) { while (sortedArray.length < x) { for (let i = 0; i < nums.length; i++) { if (min > nums[i + 1]) { min = nums[i + 1]; index = i + 1; } } sortedArray.push(min); nums.splice(index, 1); index = 0; min = nums[0]; } return sortedArray[x - 1]; } else { return 0; } } console.log(getX(2, [5, 10, -3, -3, 7, 9])); // Leave this so we can test your code: module.exports = getX;
function getX(x, nums) {
//if x is NOT in the range of the amount of numbers available in the array, return 0
if(x < 1 || x > nums.length){
   return 0;
 }
 //if it is, sort the array in order then return the number at X location in the array
 else{
   nums.sort((a,b)=>a-b);
 }
return nums[x-1]
}

module.exports = getX;

Here is my code for this chalenge, It took me sometime to understand that in the test, there were situations where x was outside the range of the array.length.
Therefore i decided to first test if x was valid and only sort the numbers once it passed the first test

-here is a more concise alternative, if we don’t mind sorting the array before checking the validity of x

function getX(x, nums) {
//sort nums in ascending order
nums.sort((a,b)=>a-b);
//return 0 if x not in the range of the array, else return number at x-1 position
return (x < 1 || x > nums.length)? 0: nums[x-1]
}
//test code
module.exports = getX;

Used bubble sort.
function getX(x, nums) {
// Write your code here
if (x > 0 && x <= nums.length && nums.length > 0) {
let swapping = true;
while (swapping) {
swapping = false;
for (let i = 0; i < nums.length -1; i++) {
if (nums[i] > nums[i+1]) {
swap(nums, i, i+1);
swapping = true;
}
}
}
console.log(nums);
return nums[x-1];
}
return 0;

}
function swap (arr, index, nextIndex) {
const temp = arr[nextIndex];
arr[nextIndex] = arr[index];
arr[index] = temp;
}

console.log(getX(2, [5, 10, -3, -3, 7, 9]));

// Leave this so we can test your code:
module.exports = getX;

Hello world This is my soluction of the excersise

function getX(x, nums) {
  nums.sort((a,b) => a - b)
  const result = nums[x - 1]
  return result ? result : 0;
}

function getX(x, nums) { nums.sort((a,b) => a - b) const result = nums[x - 1] return result ? result : 0; } console.log(getX(4, [5, 10, -3 , -3, 7, 9])); console.log(getX(2, [5, 10, -3, -3, 7, 9])); // Leave this so we can test your code: module.exports = getX;

Happy Coding!!

function getX(x, nums) {
if(nums.length===0 || x < 1 || x > nums.length){
return 0
}

let swapping=true;

while (swapping){

swapping=false;
for(let i=0; i < nums.length-1; i++){
  if(nums[i] > nums[i+1]){
    swap(nums, i, i+1);
    swapping=true;
  }
}

}

return nums[x-1];

}

const swap = (arr, index1, index2) =>{
let temp= arr[index2];
arr[index2]=arr[index1];
arr[index1]=temp;
}; // Write your code here

console.log(getX(1, [5, 10, -3, -3, 7, 9]));
console.log(getX(4, [5, 10, -3 , -3, 7, 9]));
// Leave this so we can test your code:
module.exports = getX;

function getX(x, nums) {
  // Write your code here
  let xIndex = x - 1;
  let swapping = true;
  if (x < 1 || x > nums.length) {
    return 0;
  }
  while (swapping) {
    swapping = false;
    for (let i = 0; i < nums.length; i++) {
      if (nums[i] > nums[i + 1]) {
        let temp = nums[i + 1];
        nums[i + 1] = nums[i];
        nums [i] = temp;
        swapping = true;
      }
    }
  } 
  return nums[xIndex];
}

console.log(getX(2, [5, 10, -3, -3, 7, 9])); // should return -3
console.log(getX(4, [5, 10, -3 , -3, 7, 9])); // should return 7

// Leave this so we can test your code:
module.exports = getX;

Did a simliar version in Python.

function getX(x, nums) {
 if (x > nums.length || nums.length == 0) return 0;

 let numsSorted = nums.sort((a,b) => a - b);
 return numsSorted[x-1];
}

console.log(getX(2, [5, 10, -3, -3, 7, 9]));

// Leave this so we can test your code:
module.exports = getX;
function getX(x, nums) { // Write your code here if (!nums.length || x > nums.length) return 0 const mergeSort = (arr) => { const len = arr.length if (len == 1) return arr const mid = Math.floor(len/2) const leftArr = arr.slice(0, mid) const rightArr = arr.slice(mid, len) return merge(mergeSort(leftArr), mergeSort(rightArr)) } const merge = (left,right) => { const sortedArr =[] while (left.length && right.length) { (left[0] < right[0]) ? sortedArr.push(left.shift()) : sortedArr.push(right.shift()) } return sortedArr.concat(left,right) } const sortedNums = mergeSort(nums) return sortedNums[x-1] } // Leave this so we can test your code: module.exports = getX;