Sum Chan
Sum Chan

Reputation: 1

How can simplify node script

The code is:

const _ = require('lodash');

const output = [];
let i = 0;
const inputString = "/h1/h2/h3/h4";
_.forEach(inputString.split('/').filter(e => e), (f, key, res) => {
  if (i < res.length - 1  ) {
        output.push(`/${_.slice(res, 0, i += 1).join('/')}`);
  }
});

console.log(output);

The expect output is array and skip last one : ['/h1', '/h1/h2' , '/h1/h2/h3']

How can i simplify it ? Thanks a lot !

Upvotes: 0

Views: 44

Answers (2)

vsemozhebuty
vsemozhebuty

Reputation: 13782

As a variant:

'use strict';

const inputString = '/h1/h2/h3/h4';

const arr = [...inputString].reduce((acc, ch) => {
  if (ch === '/') acc.push(`${acc[acc.length - 1] || ''}${ch}`);
  else acc[acc.length - 1] += ch;
  return acc;
}, []).slice(0, -1);

console.log(arr);

Upvotes: 0

CertainPerformance
CertainPerformance

Reputation: 370789

One option would be to split the string into the hs, slice off the empty string in the first position, and pop() the last. Then, .map the resulting array by joining indicies 0 to 0, then 0 to 1, then 0 to 2, etc:

const inputString = "/h1/h2/h3/h4";
const items = inputString.split('/').slice(1); // slice to remove empty string at [0]
items.pop(); // remove last item (h4)
const output = items.map((_, i) => '/' + items.slice(0, i + 1).join('/'));
console.log(output);

No external library required

As comment notes, another way would be to find all indicies of /:

const inputString = "/h1/h2/h3/h4";
const slashIndicies = [...inputString].reduce((a, char, i) => {
  if (char === '/') a.push(i);
  return a;
}, []);
// ignore first leading slash:
slashIndicies.shift();
const output = slashIndicies.map((slashIndex) => inputString.slice(0, slashIndex));
console.log(output);

Upvotes: 1

Related Questions