skip to Main Content

I’m trying to sort an array of 6 integers in descending order(javascript) but keep matching values in their place as the other values are sorted. An example is posted below to help explain this problem:

Input: 4, 2, 5, 4, 7, 3
Output: 4, 7, 5, 4, 3, 2

Another Example with multiple matching values:

Input: 3, 4, 3, 4, 2, 8
Output: 3, 4, 3, 4, 8, 2

If there is no matching values:

Input:
6, 2, 9, 5, 3, 4
Output:
9, 6, 5, 4, 3, 2

First you would need to check whether if any values values match, and which values match. I’m not exactly sure how to do this in this context. I’m also not sure how to sort all the other values in the array other than the matching ones. Thanks in advance!

I tried running a for loop for the length of the array that checks every number to see whether there are any matches but this caused repeated values and doesn’t get any closer to the solution

2

Answers


  1. You could use 2 maps to collect values and indices in 1 go to sort and push back to the original array:

    const tests = [
      [4, 2, 5, 4, 7, 3],
      [3, 4, 3, 4, 2, 8],
      [6, 2, 9, 5, 3, 4]
    ];
    
    function sortUniqueValues(arr, inplace = false){
      
      const found = new Map, indices = new Map;
      
      arr.forEach((v, i) => {
        const prevIdx = found.get(v);
        if(prevIdx === undefined) found.set(v, i), indices.set(i, v);
        else indices.delete(prevIdx);
      });
    
      const result = inplace ? arr : arr.slice();
      const indices2 = [...indices.keys()];
      [...indices.values()].sort((a, b) => b - a).forEach((a, i) => result[indices2[i]] = a);
      return result;
    }
    
    tests.forEach(test => console.log(...sortUniqueValues(test)));
    Login or Signup to reply.
  2. Use Javscript’s Array.prototype.sort function. It makes sorting alot easier.

    The callback gets passed two values, a and b, that need to be compared. The number you return decides where the values need to go:

    • a negative value means that a should come before b
    • a positive value means that a should come after b
    • 0 or NaN means that a and b are considered equal.

    Note: Array.prototype.sort() modifies the current arry. To create a new array, use toSorted()

    Here is an example showing how to use the sort function:

    function sortAscending(a, b) {
      return a - b;
    }
    function sortDescending(a, b) {
      return b - a;
    }
    
    function demo() {
      // Get an array of random ints
      let test = Array(6).fill().map(() => Math.floor(Math.random() * 20) + 1);
    
      // Array.prototype.sort() sorts the current array. To get a new array, use toSorted()
      console.log('Original:', test)
      console.log('Ascending:', test.toSorted(sortAscending))
      console.log('Descending:', test.toSorted(sortDescending))
    }
    
    demo()
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search