[SOLVED] Javascript – Restructure an array of strings based on prefix

Issue

I have an array containing a list of filenames:

var files = ['home_01.ai','home_02.ai','home_03.ai','imprint_01.ai','imprint_02.ai']

What I want to do is reorganise this array into a multi-dimensional array that groups together each file with the same prefix. In this case:

var firstArray = ['home_01.ai','home_02.ai','home_03.ai'], /*home*/
    secondArray = ['imprint_01.ai','imprint_02.ai']; /*imprint*/

How could I achieve that when there can be a variable amount of prefixes that can be any length in my file array?

Solution

You can loop over the array and split the filename on ‘_’ to get the prifix, then it is a case of adding those filenames into the right array, indexed by prefix.

var files = ['home_01.ai', 'home_02.ai', 'home_03.ai', 'imprint_01.ai', 'imprint_02.ai'];
var result = {};

for (var i = 0; i < files.length; i++) {
  if (files[i].indexOf('_') < 0) 
  {
    console.log("No prefix detected in '" + files[i] + "'.");
    continue;
  }
  var prefix = files[i].split('_')[0];
  if (!result[prefix])
    result[prefix] = [];
  result[prefix].push(files[i]);
}

console.log(result);

Answered By – Matt

Answer Checked By – Marie Seifert (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *