1

Here is my code

var array1 = [1,1, 30, 4, 21];
array1.sort();
console.log(array1);
// expected output: Array [1, 21, 30, 4]

I want to get the result [1,4,21,30]. the sort function should have give expected result [1,1,4,21,30] it is not giving that . Furthermore what approaches should i take just to keep one "1"? as I dont want duplications

enter image description here

Mohammad Usman
  • 37,952
  • 20
  • 92
  • 95
Mitesh
  • 1,544
  • 3
  • 13
  • 26
  • Possible duplicate of [How to sort an array of integers correctly](https://stackoverflow.com/questions/1063007/how-to-sort-an-array-of-integers-correctly) – Mohammad Usman May 05 '18 at 11:19
  • [Get all unique values in an array (remove duplicates)](https://stackoverflow.com/questions/1960473/get-all-unique-values-in-an-array-remove-duplicates) – Mohammad Usman May 05 '18 at 11:21

5 Answers5

6

You can combine sort() and reduce() just take in considiration that includes do not work in IE and as you can see in the snippet below the statement

a.includes(x) ? a : [...a, x]

represent an if statement to get rid of the duplicate element and return a single value of each element

var array1 = [1,1, 30, 4, 21];
var sortedArray1 = array1.reduce((a, x) => a.includes(x) ? a : [...a, x], []).sort()
console.log(sortedArray1);
// expected output: Array [1, 21, 30, 4]
Abslen Char
  • 3,071
  • 3
  • 15
  • 29
4

After sort you can filter your array to get rid of duplicates.

Here

var array1 = [1,1, 30, 4, 21];
array1.sort((a, b) => a - b);
var s = array1.filter(function(i, o) {
    return array1.indexOf(i) == o;
});

console.log(s)
Muhammad Usman
  • 10,039
  • 22
  • 39
4

ES6

You can also use new Set([]) and the Spread_syntax to get the required result.

DEMO

let arr= [1,1, 30, 4, 21];

arr = arr.sort((a,b)=>a-b);

console.log([...new Set(arr)])
.as-console-wrapper {max-height: 100% !important;top: 0;}
Community
  • 1
  • 1
Narendra Jadhav
  • 10,052
  • 15
  • 33
  • 44
2

You can use sort and filter at the same time. First using sort with condition a>b will give you an array with ascending values with duplicates and using filter will remove the duplicates from the sorted array.

var array1 = [1,1, 30, 4, 21];
function sort_unique(arr) {
    return arr.sort((a, b) => a>b).filter((el,i,a) => i==a.indexOf(el));
}
var res = sort_unique(array1);
console.log(res);

I recommend to use indexOf() as includes() do not work in IE browsers

Ankit Agarwal
  • 30,378
  • 5
  • 37
  • 62
1

After short just try to filter uniqueValues

var array1 = [1,1, 30, 4, 21];
array1.sort(function(a, b){return a-b});
var uniqueValues = [];


 $.each(array1, function(i, el){
        if($.inArray(el, uniqueValues) === -1) uniqueValues.push(el);
    });

console.log(uniqueValues);

Result Here: