-1

I have an array of objects, each object has property filename (string):

I would like to group these objects (on those filename property) with same naming starting from beginning to the last occurrence of $ sign.

So I would like to achieve this grupation (each group should be new array):

blue$
blue$_35    

blue_paint$
blue_paint$_35  
blue_paint$_55

01_red_carper_floor$
01_red_carper_floor$_and_roof

01_red$ 

green_car$

Some objects will have multiple while some will remain single.

I am using javascript and jquery.

I found a similar question but its not quite the same:

Find the longest common starting substring in a set of strings

Community
  • 1
  • 1
Toniq
  • 4,492
  • 12
  • 50
  • 109
  • Can you add your array to a fiddle or something? – Andy Aug 20 '15 at 12:16
  • You get the last occurence of `'$'` with [lastIndexOf](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/lastIndexOf) which you can use to [slice](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/slice). Then you can use that slice to assing the object to the right array. – Sevanteri Aug 20 '15 at 12:23

1 Answers1

1

JSFiddle

var objects = [
    {filename:"green$1"},
    {filename:"green$2"},
    {filename:"green$3"},
    {filename:"green$4"},
    {filename:"blue$1$1"},
    {filename:"blue$1"},
    {filename:"red$1"},
    {filename:"green$5"},
]

var groups = [];

for (var i = 0; i < objects.length; i++){
    var filename = objects[i].filename
    var n = filename.lastIndexOf("$");
    var groupName = filename.substring(0, n);
    if (groups[groupName] != undefined)
        groups[groupName].push(objects[i]);
    else {
        groups[groupName] = [];
        groups[groupName].push(objects[i]);
    }
}

console.log(groups);
oshell
  • 8,923
  • 1
  • 29
  • 47