简体   繁体   中英

how to seperate alphabets and numbers from an array using 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); 

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

You can do as follow:

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

Filter sounds like a good choice

 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 

You could also do it like this:

 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 ) 

You can try following using Array.sort , isNaN and String.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); 

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