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

问题:

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


回答1:

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


回答2:

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)


回答3:

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) => a-b);
arr.forEach((a,i) => {
  if(typeof a === 'number'){
    arr[i] = sortedNums[0]
    sortedNums.shift();
  } 
})

console.log(arr)


回答4:

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 a-b})
      : item
  }
).reduce(
  function(result,item){
    return result.concat(item)
  },[]
);

console.log(result);

  • 发表于 2019-02-15 17:03
  • 阅读 ( 168 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除