0

I want to organise the numbers (including duplicates) from randomNumbers in order from highest to lowest & insert them into organisedNumbers.

I think it is my while loop throwing it off but I don't understand why.

let randomNumbers = [9, 2, 6, 8, 52, 56, 7, 43, 56, 31, 48, 3, 6, 8, 4, 1, 3, 4, 5, 17, 25];
let organisedNumbers = [];

function unjumbleTwo(sourceArray, resultArray) {
  for (let i = 0, next = false; i < Math.max(...sourceArray); next === true) {
    next = false;
    let temp = sourceArray[sourceArray.indexOf(i)];
    while (typeof temp === 'number') {
      resultArray.push(temp);
    }
    next = true;
  }
};
unjumbleTwo(randomNumbers, organisedNumbers);
console.log(organisedNumbers);

Edit: 'i' never changed. Fixed and got rid of 'next === true, false'.

function unjumble(sourceArray,resultArray){
  for (let i = 0; i < Math.max(...sourceArray); i++){
    let temp = sourceArray[sourceArray.indexOf(i)];
    while (typeof temp === 'number'){
      resultArray.push(temp);
    }
  }
};
unjumble(randomNumbers,organisedNumbers);
console.log(organisedNumbers);
6
  • Hey, why are you doing it manually ? There's library or native methods to do this. take a look on sort() method Commented Feb 4, 2019 at 14:54
  • I think the for-loop is misused. next === true seems weird to me Commented Feb 4, 2019 at 14:54
  • where are you changing the i? Commented Feb 4, 2019 at 14:55
  • const organisedNumbers = [9, 2, 6, 8, 52, 56, 7, 43, 56, 31, 48, 3, 6, 8, 4, 1, 3, 4, 5, 17, 25].slice(0).sort((a,b) => a-b); console.log(organisedNumbers); Commented Feb 4, 2019 at 14:56
  • And yes, you never get a new temp inside the while loop and never stop Commented Feb 4, 2019 at 15:01

2 Answers 2

-1

Just return it like this:

randomNumbers.sort((a,b) => a > b ? 1 : a < b ? -1 : 0);

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

1 Comment

1. HUGE duplicate. 2. You mutate the original
-1

You can use sort function:

let randomNumbers = [9,2,6,8,52,56,7,43,56,31,48,3,6,8,4,1,3,4,5,17,25];
let organisedNumbers = randomNumbers.sort((a, b) => b - a);

console.log(organisedNumbers)

1 Comment

1. Huge dupe and 2. You mutate the original. Sort works in situ

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.