0

I would like to split an array into two arrays (one for letters and the other for frequencies).

var list = [ "ES 324798", "LE 237076", "EN 231193" ]

This is the array that I want to split.

I would like to get an array with all letters like this :

var letters = [ "ES", "LE", "EN" ]

And an other with numbers :

var numbers = [ "324798", "237076", "231193" ]

I searched for "how to split one array in two arrays with React native" but I don't find what I want. I tried with split and splice functions but it didn't help me (or I just don't know how to use them properly).

Can you give me some tips ?

2 Answers 2

3

One possible solution could be using .reduce() and .split().

Try the following:

const list = [ "ES 324798", "LE 237076", "EN 231193" ];

const result = list.reduce((a, c) => {
  const split = c.split(' ');
  a.letters.push(split[0]);
  a.numbers.push(split[1]);
  return a;
}, { letters: [], numbers: [] });

const { letters, numbers } = result;

console.log('letters', letters);
console.log('numbers', numbers);

I hope this helps!

Sign up to request clarification or add additional context in comments.

1 Comment

Why my first element "ES" isn't in the both arrays ? getBigrams = () => { List.reduce((a, c) => { const split = c.split(' '); this.state.BigramsLetters.push(split[0]); this.state.BigramsFrequency.push(parseInt(split[1], 10)); return a; }) console.log('letters', this.state.BigramsLetters); console.log('numbers', this.state.BigramsFrequency); }
1

This is not about React Native.

I would do:

const letters = []
const numbers = []
list.forEach((item) => {
  const [ letter, number ] = item.split(' ')
  letters.push(letter)
  numbers.push(number)
})

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.