Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort only number values in array?

var points = [2, a, t, 5, 4, 3]; and after sort: var points = [2, a, t, 3, 4, 5];

Any help about that? it is possible to post your help with old style javascript code because i work on Adobe DC project?

my code is there :

var points = [t1, t2, t3, t4];
[t1, t2, t3, t4] = points;

var lucky = points.filter(function(number) {
  return isNaN(number) == false && number !=="" && number!== undefined;
});
points=lucky
points.sort(function(a, b){return a - b});

this.getField("Text6").value = points

but this only sort min to max and filter other characters... i need to keep other characters and short only numbers...

like image 614
hacker tom Avatar asked Feb 14 '19 11:02

hacker tom


2 Answers

var points = [2, "a", "t", 5, 4, 11, "", 3];
var insert = points.slice(0); // Clone points

// Remove all elements not a number
points = points.filter(function(element) {
  return typeof element === 'number';
});

// Sort the array with only numbers
points.sort(function(a, b) {
  return a - b;
});

// Re-insert all non-number elements
insert.forEach(function(element, index) {
  if (typeof element !== 'number') {
    points.splice(index, 0, element);
  }
});

console.log(points);
like image 171
Armel Avatar answered Oct 17 '22 03:10

Armel


You may be able to do this more efficiently by avoiding splice() if you simply reassign the values in place.

Filter, sort, the reassign to sort the numbers in place:

let arr = ['c', 2, 'a', 't', 5, 4, 3, 'b', 1]

let n = arr.filter(c => typeof c == "number").sort((a, b) => a-b)
for (let i = 0, c=0; i<arr.length; i++){
    if (typeof arr[i] == "number") arr[i] = n[c++]
}
console.log(arr)
like image 2
Mark Avatar answered Oct 17 '22 05:10

Mark