简体   繁体   中英

How to sort array values alphabetically and create sub array of values starting with same characters in javascript

I need help to sort an array alphabetically and then combine them in sub arrays in JavaScript.

for example:

var arrayAll = ['1test', '100_test', 'andrew', 'andy', 'bittu', 'ben', 'bigB', 'chandan', 'chan', 'chetan', 'chaitali', ..............] ;

I need to convert this as below:

 var arraname = [['100_test','1test'],['andy','andrew'],[ 'ben',  'bigB','bittu'],[ 'chan','chandan', chaitali,'chetan'],[...]...];

What can be the Javascript logic for this?

You could sort the array and build groups based on the first character of every string.

 var array = ['1test', '100_test', 'andrew', 'andy', 'bittu', 'ben', 'bigB', 'chandan', 'chan', 'chetan', 'chaitali'], grouped = array .sort() .reduce(function (r, a) { if ((r[r.length - 1] || [''])[0][0] === a[0]) { r[r.length - 1].push(a); } else { r.push([a]); } return r; }, []); console.log(grouped);
 .as-console-wrapper { max-height: 100% !important; top: 0; }

For same upper/lower case letters, you could use a hash table for grouping and an case insensitive sorting.

 var array = ['1test', '100_test', 'Andrew', 'andy', 'bittu', 'ben', 'BigB', 'chandan', 'chan', 'chetan', 'chaitali'], hash = Object.create(null), grouped = []; array .sort(function (a, b) { return a.localeCompare(b, undefined, { numeric: true, sensitivity: 'base' }); }) .forEach(function (a) { var key = a[0].toLowerCase(); if (!hash[key]) { hash[key] = []; grouped.push(hash[key]); } hash[key].push(a); }); console.log(grouped);
 .as-console-wrapper { max-height: 100% !important; top: 0; }

You can first sort the array, then use reduce to group them based on their character value at index 0 and then filter out the empty array.

 var arrayAll = ['1test', '100_test', 'andrew', 'andy', 'bittu', 'ben', 'bigB', 'chandan', 'chan', 'chetan', 'chaitali'] ; arrayAll.sort(); var result = arrayAll.reduce((r,a) => { let pos = a.charCodeAt(0) < 'a'.charCodeAt(0) || a.charCodeAt(0) > 'z'.charCodeAt(0) ? 0 : a.charCodeAt(0) % 'a'.charCodeAt(0) + 1; r[pos].push(a); return r; }, Array.from({length:27}, _ => [] )); let arrname = result.filter(x => x.length); console.log(arrname);

At first you can create object (associative array), then you can loop thru all your items in arrayAll and add them to object. After that you can sort them by object keys and finaly create array as in this post: convert Object {} to array [] in javascript , but leaving only obj[key] . Note that obj[key] should be array that you have added elements to

您可以使用Array.prototype.sort()对数组进行排序,然后使用ASCII 代码表创建子数组并通过 for 循环将它们推送到新数组中。

Try this:

This is working and it's easier to understand

JS Fiddle

I'll try to optimize it, I am also a rookie in JS.

 function go(){ var arrayAll=['1test', '100_test', 'andrew', 'andy', 'bittu', 'ben', 'bigB', 'chandan', 'chan', 'chetan', 'chaitali']; arrayAll.sort(); var arrayName = []; var temp =[]; while(arrayAll.length) { temp=[]; var startingChar = arrayAll[0].charAt(0); for(i=0;i<arrayAll.length;) { i=0; var pos = arrayAll[i].indexOf(startingChar); if( pos== 0) { var poppedChar = arrayAll.splice(pos,1); temp.push(poppedChar[0]); } else break; } arrayName.push(temp); } console.log(arrayName); } $(document).ready(function(){ go(); });
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Sort the array first.

var array = ['1test', '100_test', 'andrew', 'andy', 'bittu', 'ben', 'bigB', 'chandan', 'chan', 'chetan', 'chaitali'];
var sortedArray = sorting(array);

function sorting(data) {
    data.sort(function(a, b) {
    var nameA = a.toUpperCase(); // ignore upper and lowercase
    var nameB = b.toUpperCase(); // ignore upper and lowercase
    if (nameA < nameB) {
        return -1;
    }
    if (nameA > nameB) {
        return 1;
    }
    // names must be equal
    return 0;
});
return data;
}

grouping according to alphabet

 var arrayName = createSection(sortedArray);

function createSection(dataAll) {
//according to name data is stored...
var temp = {}
var profile = [];
dataAll.forEach(function(element) {
    var name = element.toUpperCase();
    var id = name.charAt(0);
    if (!(temp[id] && temp[id].length)) {
        temp[id] = [];
    }
    temp[id].push(element);
});
 for (var k in temp){
   profile.push(temp[k]);
}
console.log(profile);
return profile;
}
console.log(arrayName);

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