0

The question of the challenge is :

Modify the function to return a copy of the given array sorted in ascending order (1, 2, 3, etc). Do not modify the original array.

I've tried doing a normal for loop and an if statement :

let original = [1, 7, 3, 5];
let sortedCopy = []
for (i = 0; i < original.length; i++){
    if (original[i] > original[i+1]){
        sortedCopy.push.([1])
    } 
}
console.log(sortedCopy);

Now I'm trying to use a .map method since it automatically loops and passes each number through the callback

function copyAndSortNumbers(numbers) {
  this.numArray = numbers;
  numArray.map(sortingArray)
  function sortingArray (numbers){
    if (numbers[i] > numbers[i+1]){
      return numbers;
    }
  }
}

const original = [1, 7, 3, 5];
const sortedCopy = copyAndSortNumbers(original);

I should get a new ordered array but I don't see what I'm missing

Edit:

here is an updated version, it's now returning an array but still not sorting it

function copyAndSortNumbers(numbers) {
  numArray = numbers;
  numArray.map(sortingArray)
  function sortingArray (numbers){
    if (numbers > numbers + 1){
      return numbers;
    }
  }
  return numArray;
}
3
  • 4
    1. That's not what .map() should be used for 2. Have a look at: Array.prototype.map() on how .map() works and what the arguments of the callback are Commented Feb 7, 2019 at 12:06
  • .map() !== .sort() Commented Feb 7, 2019 at 12:09
  • "How can I use .map() to sort items" - you don't. I'm really puzzled by the amount of people who seem to use .map() things it's not supposed to. And by this I mean as a replacement to .forEach(). I'm not sure where that misconception is coming from. Commented Feb 7, 2019 at 13:01

4 Answers 4

7

You can use slice to copy the array and then sort to sort the new array.

const original = [1, 7, 3, 5];
const sorted = original.slice().sort((a, b) => a - b)

console.log(original, sorted)

Comparison of array copy method speed.

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

Comments

2

For getting a sorted array, you need two nested loops, one for the given array and one for finding the position for inserting the actual element.

var array = [1, 7, 3, 5],
    copy = array.slice(0, 1),
    i, j;
  
outer: for (i = 1; i < array.length; i++) {
    for (j = 0; j < copy.length; j++) {
        if (array[i] < copy[j]) {
            copy.splice(j, 0, array[i]);
            continue outer;
        }
    }
    copy.push(array[i]);
}

console.log(copy);

2 Comments

So the first loop iterates through each element of the array and the second loop iterates trough each element of the loop and checks to if the iterated item of the array is smaller than the iterated item of the copy array and if true, it adds the item onto the array?
right. it splices the copy array and inserts the item at the position or if the loop of the copy does not found any value which is smaller than the item, then it pushes the item to (the end of) the array.
1

Using the spread syntax may be simpler and returns a new array.

const initial = [1, 7, 3, 5];
const sorted = [...initial].sort((a, b) => a - b)

console.log(initial, sorted)

1 Comment

Spread is currently pretty slow: jsperf.com/jc-array-copy-methods. Worth noting if performance is a concern.
0

Lots. First of all,

numArray.map(sortingArray)

should throw an error because numArray is not defined. You have this.numArray, which is not the same thing. If that weren't an issue, the line does nothing, since you don't assign the result to anything. But even that doesn't work, because i is undefined in your callback... and the callback does no sorting, whatsoever.

To create a copy of an array, you can use let copy = numbers.slice(), let copy = Array.from(numbers), let copy = [...numbers], or indeed let copy = numbers.map(x => x); this last one is the slowest EDIT: Apparently, Array.from is currently slowest, and destructuring is slow on Firefox, which actually executes map as fast as slice. Go figure. A good reminder even to veterans never to assume performance without testing.

To sort that copy then, copy.sort((a, b) => a - b) suffices.

2 Comments

I'm sure that will change over time as it gets better optimised. Probably has a lot of overhead for type checking though.
@JamesCoyle: Thinking more about it, both slice and map are native to Array, while Array.from has to go through an iterator. map being as fast as it is surprised me, but it might be that the identity function gets optimised away...

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.