Javascript alphabetical grouping

大兔子大兔子 提交于 2019-12-11 05:02:02

问题


I have a json array of objects that look like this: {id:'the id', name:'the name'}; and I need to loop over the array and group each object alphabetically by it's name attribute. Is there a way to do this without using a switch / if statement with every letter in it?

What I don't want to do is something like this:

if(data[i].name..slice(0, 1) == 'a') {
   ...
}

It's a large array, with almost a 1,000 objects in it. My goal is eventually append them to a dive so it looks something like this:

4

  • 4 pints
  • 4 biscuits

A

  • Apple
  • Alex
  • Adam

B

  • Bob
  • Billy

回答1:


you can loop throught your collections like this:

var groupedCollection = {};   
for(...){//loop throug collection         
    var firstLetter = data[i].charAt(0);
    if(groupedCollection[firstLetter] == undefined){             
        groupedCollection[firstLetter] = [];         
    }         
    groupedCollection[firstLetter].push(data[i]);     
}
//groupedCollection now contait data in the form of {a: [], b:[], etc...}



回答2:


Bubble sort will do this job for you. Example:

// sample array
var myArr = [
    {id:"00", name:"Billy"},
    {id:"00", name:"Apple"},
    {id:"00", name:"4 biscuits"},
    {id:"00", name:"Adam"},
    {id:"00", name:"Alex"},
    {id:"00", name:"4 pints"},
    {id:"00", name:"Bob"}
];

// standard bubble sort algorithm
function bubbleSortByName(arr) {
    for (var x = 0; x < arr.length; x++) {
        for(var y = 0; y < arr.length-1; y++) {
            // compare arr[].name.toLowerCase() i.e. b > a
            if(arr[y].name.toLowerCase() > arr[y+1].name.toLowerCase()) {
                var tmp = arr[y+1];
                arr[y+1] = arr[y];
                arr[y] = tmp;
            }
        }
    }
    return arr; 
}

// sort the array
var sortedArr = bubbleSortByName(myArr);

// print the results
for (var i=0; i<sortedArr.length; i++)
    document.write(sortedArr[i].name+"<br/>");

Or the same idea with an insertion sort algorithm:

// standard insertion sort algorithm
function insertionSortByName(arr) {
    for(var j = 1; j < arr.length; j++) {
        var key = arr[j];
        var i = j - 1;

        while(i >= 0 && arr[i].name.toLowerCase() > key.name.toLowerCase()) {
            arr[i+1] = arr[i];
            i = i - 1;     
        }            

        arr[i+1] = key;
    }

    return arr;
}



回答3:


ES7 syntax

const sortAndGroup = async () => {
  const sortedData = data.sort();
  const reducedData = sortedData.reduce((items, dataElement) => {
    if (!items.find(item => item.header === dataElement.charAt(0))) {
      items.push({ header: dataElement.charAt(0) });
    }
    items.push({ name: dataElement });
    return items;
  }, []);
  return reducedData.map(item => item.header || item.name);
};


sortAndGroup().then(result => console.log(result));


来源:https://stackoverflow.com/questions/5875938/javascript-alphabetical-grouping

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!