1

I have a function where I get the following array:

var result = ["a-x-y", "b+x+y", "b+x+y", "b+x+y", "c_x_y", "c_x_y", "d_x_y"];

As a result, however, I would only like to receive the string with the attached special character and the number of occurrences only once:

var result = ["a-x-y~1", "b+x+y~3", "c_x_y~2", "d_x_y~1"]

Here the function:

var folders = ["a-x-y_1", "b+x+y_1", "b+x+y_3", "b+x+y_2", "c_x_y_1", "c_x_y_2", "d_x_y_1"];

folders.forEach(function (item) {
  var index = item.lastIndexOf("_");
  var result = item.substring(0, index);
  console.log(result);
});
patrick
  • 33
  • 5

2 Answers2

0

You could for example use a Map to count the number of occurrences. Use the first item from split as the key and start with 1.

For every same key, increment the value by 1.

Assuming all the values have a an underscore present:

const folders = ["a_x_y_1", "b_x_y_1", "b_x_y_3", "b_x_y_2", "c_x_y_1", "c_x_y_2", "d_x_y_1"];
const m = new Map();

const result = folders.forEach(folder => {
  const part = folder.slice(0, folder.lastIndexOf('_'));
  !m.has(part) ? m.set(part, 1) : m.set(part, m.get(part) + 1);
})

for (const [key, value] of m.entries()) {
  console.log(`${key}~${value}`);
}
The fourth bird
  • 154,723
  • 16
  • 55
  • 70
  • @ The fourth bird: Thank you for your prompt reply, but it could happen that a string of the array also contains several underlines so only the last one has to be cut off. i have adapted the question and the code accordingly. – patrick Mar 23 '21 at 21:32
  • @ The fourth bird: I have adjusted the question again. – patrick Mar 23 '21 at 21:40
  • @patrick I have updated the answer. You can take the part before the last underscore as a key. – The fourth bird Mar 23 '21 at 21:41
0

You could count and join the result.

const
    array = ["a_x_y", "b_x_y", "b_x_y", "b_x_y", "c_x_y", "c_x_y", "d_x_y"],
    result = Array.from(
        array.reduce((m, k) => m.set(k, (m.get(k) || 0) + 1), new Map),
        a => a.join('~')
    );

console.log(result);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392