简体   繁体   中英

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...

 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); 

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) => ab) for (let i = 0, c=0; i<arr.length; i++){ if (typeof arr[i] == "number") arr[i] = n[c++] } console.log(arr) 

filter() numbers out of array. Then sort() them and then loop through real array. And check if value is Number change it will first element of sorted array. And remove first element of sortedArr

 let arr = [5, 't', 's', 2,3,4]; let sortedNums = arr.filter(x => typeof x === 'number').sort((a,b) => ab); arr.forEach((a,i) => { if(typeof a === 'number'){ arr[i] = sortedNums[0] sortedNums.shift(); } }) console.log(arr) 

The following should give the exact output given your input:

 var result = [2, 'a', 't', 5, 4, 3].reduce( function(result,item){ return !isNaN(item)&&item!=='' ? typeof (result[result.length-1] && result[result.length-1].push) === 'function' ? (result[result.length-1].push(item),result) : result.concat([[item]]) : result.concat(item) }, [] ).map( function(item){ return typeof item.sort === 'function' ? item.sort(function(a,b){return ab}) : item } ).reduce( function(result,item){ return result.concat(item) },[] ); console.log(result); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM