vgogov
vgogov

Reputation: 77

Angular 2 Custom Alphabetical Pipe Sort

Let's say I have an array of strings:

this.data = [ 'cupcake', 'donut', 'eclair', 'froyo', 'gingerbread', 'icecream', 'lollipop', 'marshmallow', 'nougat', 'oreo' ]

I can sort these alphabetically using the pipe:

@Pipe({
name: 'alphabeticPipe'
})

export class AlphabeticPipe implements PipeTransform {
transform(data: any[], searchTerm: string): any[] {
  data.sort((a: any, b: any) => {
  if (a < b) {
    return -1;
  } else if (a > b) {
    return 1;
  } else {
    return 0;
  }
});
return data;
}
}

My question is how could I sort these with a custom alphabetical order, for example I want "e" to show first, then "g", then "m" etc. So the order will look like: eclair, gingerbread, marshmallow and the rest can follow alphabetical order or anything else specified?

Thanks for the help!

Upvotes: 1

Views: 1153

Answers (1)

Icycool
Icycool

Reputation: 7179

Took me a while to figure out a good way to represent it.

Note that in this implementation e is always in front of a, so ee is sorted in front of ea

var data = [ 'cupcake', 'donut', 'eclair', 'froyo', 'gingerbread', 'icecream', 'lollipop', 'marshmallow', 'nougat', 'oreo' ]

data.sort(function(a, b) {
  var i = 0;
  
  while (true) {
    if (i > a.length && i > b.length) return 0;
    else if (i > a.length) return -1;
    else if (i > b.length) return 1;
    else {
      var compare = compareChar(a.charAt(i), b.charAt(i));
      if (compare != 0) return compare;
      i++;
    }
  }

  function compareChar(a, b) {
    var special = ["e", "g", "m"];
    
    var ia = special.indexOf(a);
    var ib = special.indexOf(b);

    if (ia != -1 && ib != -1) { // both special char
      return (ia == ib) ? 0 : (ia < ib) ? -1 : 1;
    }
    else if (ia != -1 && ib == -1) {
      return -1;
    }
    else if (ia == -1 && ib != -1) {
      return 1;
    }
    else {
      return (a == b) ? 0 : (a < b) ? -1 : 1;
    }
  }
});

document.body.innerHTML = data.toString();

Upvotes: 3

Related Questions