Populating a JavaScript Array where elements in one array need to partially match another, and then be combined

Advertisements

I have two arrays, one which contains option codes and another which contains their descriptions. What is the most efficient way of creating an array that contains both the code and it’s definition?

the first array looks like this and contains the code

[ '1CA', '1CD', '205', '258', '2K1', '2VH', '302', '322', '386', '3AG', '417', '423', '428', '430', '431', '441', '459', '494', '4BN', '4UR', '4UY', '502', '508', '522', '524', '534', '571', '601', '609', '644', '676', '698', '6VC', '812', '823', '845', '853', '876', '8KA', '8S1', '8S3', '8TM', '925', '992', '9AA' ]

and the second array looks like this and contains the code (although with an S and A either side) and it’s definition.

['S000A Dummy-SALAPA\n',
    'S001A Nat.vers. not controlled as package\n',
    'S0BVA Refueling until tank full\n',
    'S0BWA Partial fueling\n',
    'S100A Usable load increase\n',
    'S102A Chassis, officials utility vehicle\n',
    'S102A Reinforced brakes\n',
    'S103A Four seasons tyres\n',
    'S103A Aggregate protective plate\n',
    'S115A Paramedic sticker NRW\n',
    'S115A NRW Fire-brigade Sticker\n',
    'S4BNA Fine-wood trim ash grain\n',
    'S117A Banner staff, right\n',
    'S160A Installation, Becker Signal Syst.LU 322\n',
    'S161A Emissions standard EU5\n']

>Solution :

It looks like the only code that has a corresponding definition is 4BN:

const codes = [
  '1CA', '1CD', '205', '258', '2K1', '2VH', '302', '322',
  '386', '3AG', '417', '423', '428', '430', '431', '441',
  '459', '494', '4BN', '4UR', '4UY', '502', '508', '522',
  '524', '534', '571', '601', '609', '644', '676', '698',
  '6VC', '812', '823', '845', '853', '876', '8KA', '8S1',
  '8S3', '8TM', '925', '992', '9AA',
];

const definitions = [
  'S000A Dummy-SALAPA\n',
  'S001A Nat.vers. not controlled as package\n',
  'S0BVA Refueling until tank full\n',
  'S0BWA Partial fueling\n',
  'S100A Usable load increase\n',
  'S102A Chassis, officials utility vehicle\n',
  'S102A Reinforced brakes\n',
  'S103A Four seasons tyres\n',
  'S103A Aggregate protective plate\n',
  'S115A Paramedic sticker NRW\n',
  'S115A NRW Fire-brigade Sticker\n',
  'S4BNA Fine-wood trim ash grain\n',
  'S117A Banner staff, right\n',
  'S160A Installation, Becker Signal Syst.LU 322\n',
  'S161A Emissions standard EU5\n',
];

const definitionsMap = new Map(definitions.map(s => {
  const [code, ...definition] = s.split(' ');
  return [code.substring(1, 4), definition.join(' ').trimEnd()];
}));

const codesWithDefinitions = codes.map(c => ({code: c, definition: definitionsMap.get(c)}))
                                  .filter(c => c.definition);
console.log(codesWithDefinitions);

Leave a ReplyCancel reply