1

There is a 2 dimensional array:

    let userGroup = [
    ['user1-', 'user2-', 'user3-'],
    ['user4-', 'user5-', 'user6-'], 
    ['user7-', 'user8-', 'user9-']
];

How to make a single array from it and delete the symbol "-" after each element?

So the output will be: ['user1, 'user2', 'user3', 'user4', 'user5', 'user6', 'user7', etc...]

And also how to write a code which will do the same but with any number of inner arrays? For example if the "userGroup" array had more unexpected inner arrays with more users (['user11', 'user12', 'user13] etc.), what is the way to write a function which take the "userGroup" array and will do the same (delete the last element "-" in each element and combine all the elements in inner arrays into one array)?

6 Answers 6

2

Reduce is one way, can use also the new-ish flat method; by default it flattens only to single level but possible to define depth

userGroup.flat().map(item => item.slice(0, -1));
Sign up to request clarification or add additional context in comments.

Comments

1

Try this:

 console.log(userGroup.reduce((acc, curr)=> [...acc, ...curr], [])
    .map(el => el.replace('-','')));

Comments

1

For a one liner, consider:

const mapped = userGroup.reduce((p,c) => p.concat(c), []).map(s => s.slice(0, s.length-1));

Comments

1

Try this

[].concat.apply([], userGroup).toString().split('-,');

Comments

1

Array.prototype.flat is the one you are looking for

userGroup.flat()

and then you will have the flat array for your array of arrays.

Then user the Array.prototype.map to convert the values as you like

userGroup.flat().map(m => m.replace('-', ''));

Comments

1

You need few things to achieve your goal.

  1. .replace()

const u = 'user1-';

console.log(u.replace('-', ''));

  1. .map()

const u = ["user1-", "user2-", "user3-"];

const m = u.map(i => i.replace("-", ""));

console.log(m);

  1. .flat()

const u = [
  ["user1-", "user2-"],
  ["user3-", "user4-"]
];

console.log(u.flat());

So, combing all the 3 methods in a single statement, the below is the code:

let userGroup = [
  ['user1-', 'user2-', 'user3-'],
  ['user4-', 'user5-', 'user6-'],
  ['user7-', 'user8-', 'user9-']
];

   let grouped = userGroup.flat().map(item => item.replace('-', ''));
   console.log(grouped)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.