0

Как из такой Organization/LimitedCompany/HousingCooperative строки можно сделать массив такого вида: ['Organization', 'Organization/LimitedCompany', 'Organization/LimitedCompany/HousingCooperative']?

2 ответа 2

2

let str = 'Organization/LimitedCompany/HousingCooperative',
  temp = null,
  result = [];
let data = str.split('/');

data.forEach(function(item, index, array) {
  temp = (temp !== null) ? temp + '/' + item : item;
  result.push(temp);
});

console.log(result);

1

Вариант с reduce:

let str = 'Organization/LimitedCompany/HousingCooperative';
let data = str.split('/');

let result = data.reduce((acc, item, i) => {
  acc.push((i ? acc[i - 1] + '/' : '') + item);
  return acc;
}, [])

console.log(result)

И с map:

let str = 'Organization/LimitedCompany/HousingCooperative';
let data = str.split('/');

let result = data.map((item, i, arr) => arr.slice(0, i + 1).join('/'));
console.log(result);

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.