如何使用javascript从数组中分离字母和数字

时间:2018-10-12 08:56:37

标签: javascript

数组输入为

var a =[1,'a',2,3,'e',4,'r'];

我试图通过以下方法检查此字符串的长度,以将该数组转换为字符串

我想将数组转换为

    ['a','e','r',1,2,3,4]

这是正确的做法吗?

var a = [1, 'a', 2, 3, 'e', 4, 'r'];
var b = a.toString();
console.log(b);
var num, alpha;
for (var i = 0; i < b.length; i++) {
  var letters = /[A-Za-z]+$/;
  var numbers = /[0-9]/;
  if (b.charAt(i).match(numbers))
    num.append(b.charAt(i));
  else if (b.charAt(i).match(letters))
    alpha.append(b.charAt(i));
}

console.log(alpha);
console.log(num);

5 个答案:

答案 0 :(得分:4)

您可以通过获取数字支票的差额来对数组进行排序。

var array = [1, 'a', 2, 3, 'e', 4, 'r'];

array.sort((a, b) => (typeof a === 'number') - (typeof b === 'number'));

console.log(array);

答案 1 :(得分:3)

您可以执行以下操作:

var a =[1,'a',2,3,'e',4,'r'];
var a_word = [];
var a_number = [];
a.forEach(current=>{
  if(typeof(current)==="number")
    a_number.push(current);
  if(typeof(current)==="string")
    a_word.push(current);
});
var result = a_word.concat(a_number);
console.log(result);

答案 2 :(得分:1)

过滤器听起来是个不错的选择

var a =[1,'a',2,3,'e',4,'r'];

var newArr = [];
var num = a.filter(function(num) {
  if (isNaN(num)) newArr.push(num)
  return !isNaN(+num)
});
console.log([...newArr,...num]); // create a new array
newArr = newArr.concat(num); // or reuse
console.log(newArr)

// or just

console.log(a.sort()); // will sort numbers first

答案 3 :(得分:1)

您也可以这样:

const a = [ 1, 'a', 2, 3, 'e', 4, 'r' ]

const b = a.reduce( ( acc, item ) => {
  if ( typeof item == 'number' ) {
    acc.push( item )
  } else {
    acc.unshift( item )
  }
  return acc
}, [] ).sort( ( a, b ) => a > b )

console.log( b )

答案 4 :(得分:1)

您可以尝试使用Array.sortisNaNString.localeCompare

let a =[1,'a',2,3,'e',4,'r'];
a.sort((b,c) => isNaN(c) - isNaN(b) || String(b).localeCompare(String(c)))
console.log(a);