-1

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?

Shivam Sharma
  • 1,277
  • 15
  • 31
  • Why should `1test` come before `100_test` or `bittu` before `ben` and `bigB`? Also read [Why is “Can someone help me?” not an actual question?](http://meta.stackoverflow.com/q/284236). What have you tried? – Sebastian Simon Oct 17 '17 at 06:01
  • apologies, these can be any string values not in sequenced, –  Oct 17 '17 at 13:12

6 Answers6

1

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; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • Its working fine for me but it contains more than 27 array elements, with Upper case and lower cased values are separated. what if I dont wish to use toLowerCase for my array elements any suggestion? –  Oct 17 '17 at 09:40
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);
Hassan Imam
  • 21,956
  • 5
  • 41
  • 51
0

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

NoOorZ24
  • 2,914
  • 1
  • 14
  • 33
0

You can use Array.prototype.sort() to sort your array and then ASCII code tables to create sub arrays and push them into a new array through a for loop.

Marzieh Bahri
  • 554
  • 7
  • 20
0

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>
Shivam Sharma
  • 1,277
  • 15
  • 31
0

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