Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to seperate alphabets and numbers from an array using javascript

Tags:

javascript

Array Input as

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

I have tried to convert this array to string and by checking the length of the string as below

I want to convert the array to

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

Is this a correct way of doing?

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);
like image 661
valli Avatar asked Dec 09 '25 17:12

valli


1 Answers

You could sort the array by taking the delta of the check for number.

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

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

console.log(array);
like image 162
Nina Scholz Avatar answered Dec 12 '25 06:12

Nina Scholz