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 ?
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!
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)
})
Related
I am trying to write javascript code that allows me to extract which words (given as a list) contain either 1 or more characters in a given list of words.
function filterWords(words, letters) {
var myArrayOfLetters = Array.from(letters)
var output;
for(var i = 0; i<myArrayOfLetters.length; ++i)
{
output = words.filter(word => word.includes(myArrayOfLetters[i]))
}
return output;
}
This is the code I have so far but it is not working.
This is an example of the input and the output required:
words = ['the','dog','got','a','bone']
letters = 'ae'
output = ['the','a','bone']
As you can see the output contains all the words that have either 'a' or 'e' in them or both.
How would I go about solving this issue?
You're on the right track, but you have your loops backward. You want to use the filter as the outer loop, and the loop over the array of letters as the inner loop, since you want to know if a word has any of those letters in it. The inner loop can be a call to the some method rather than an explicit loop:
function filterWords(words, letters) {
const myArrayOfLetters = Array.from(letters);
const output = words.filter((word) =>
myArrayOfLetters.some((letter) => word.includes(letter))
);
return output;
}
some returns true if the callback ever returns true (or any truthy value), or false if the callback never does.
Live Example:
function filterWords(words, letters) {
const myArrayOfLetters = Array.from(letters);
const output = words.filter((word) => myArrayOfLetters.some((letter) => word.includes(letter)));
return output;
}
const words = ["the", "dog", "got", "a", "bone"];
const letters = "ae";
console.log(filterWords(words, letters));
Here's an example with a word that has both a and e in it; note it's only included once:
function filterWords(words, letters) {
const myArrayOfLetters = Array.from(letters);
const output = words.filter((word) => myArrayOfLetters.some((letter) => word.includes(letter)));
return output;
}
const words = ["the", "dog", "got", "a", "really", "nice", "bone"];
const letters = "ae";
console.log(filterWords(words, letters));
You can simply achieve it with the help of Array.filter() along with Array.some() method.
Live Demo :
let words = ['the', 'dog', 'got', 'a', 'bone'];
const letters = 'ae';
const splittedLetters = letters.split('');
const res = words.filter(item => {
return splittedLetters.some(word => item.includes(word));
});
console.log(res);
let words = ['javascript', 'java', 'ruby', 'python', 'php'];
let filterWords =(words, chars) => {
return words.filter(word => word.split('').some(char => chars.includes(char)));
}
console.log(filterWords(words, 'pa')); //['JavaScript', 'Java', 'Python', 'PHP']
I have an array of strings like this. Both left and right portions in the string are separated with spaces (More than 1 space for each).
const arr = [
'A1789 Other tuberculosis of nervous system',
'A179 Tuberculosis of nervous system, unspecified',
'A1801 Tuberculosis of spine'
];
I need to turn this into an array of objects like this, with the first portion as the key and the second portion as the value of the key.
const arrOfObj = [
{ A1789: 'Other tuberculosis of nervous system' },
{ A179: 'Tuberculosis of nervous system, unspecified' },
{ A1801: 'Tuberculosis of spine' }
];
I would split by space, assuming your key cannot contain space. So we'll have first item your key and the "rest" your value, which we can trim
arr.map(s => {
const [key, ...value] = s.split(" ");
return { [key]: value.join(" ").trim() }
})
I'd think something like this would work:
const arrOfObj = {};
arr.forEach(item => {
const match = str.match(/^([A-Za-z0-9]+)\s+(.+)/);
arrOfObj[match[1]] = match[2];
});
Hi below is array of strings
const arr = [
"list/1/item/1/",
"some-domain/2/item/2/",
"item/3/",
"some-domain/4/item/5/subitem/1/",
]
i have to filter those strings that start with string "item/3/" or ends with string "item/3/"
so from above array expected filtered array is like below,
const filtered_arr = [
"list/1/item/1/",
"some-domain/2/item/2/",
"item/3/",
]
from the filtered array i want to get the number after "/item/". so from above filtered array the expected output is
const arr_ids = ["1", "2", "3"]
what i have tried,
i have used below to match those strings that start or end with /item/3/
const filtered_arr = arr.map(str) => {
return str.match(/item\/[0-9](\/)?$/g);
}
this gives the filtered_arr
const filtered_arr = [
"list/1/item/1/",
"some-domain/2/item/2/",
"item/3/",
]
but how do i map through each array item and get the number after string "/item/".
could someone help me with this. thanks.
Use filter to filter paths either starting or ending in item/\d+/. Then use map to extract the item number from each matching path.
const arr = [
"list/1/item/1/",
"some-domain/2/item/2/",
"item/3/",
"some-domain/4/item/5/subitem/1",
];
var output = arr.filter(x => x.match(/^item\/\d+|\bitem\/\d+\/$/))
.map(x => x.match(/(?<=^item\/)\d+|(?<=\bitem\/)\d+(?=\/$)/)[0]);
console.log(output);
This may help:
const filtered_arr = arr.map(str) => {
const match = str.match(/\/item\/(\d)/);
return(match[1]);
}
I need to convert a string into an array with 4 elements, each element has maximum of 4 characters.
"1234567812345678" -> ["1234", "5678", "1234", "5678"]
"12345678123" -> ["1234", "5678", "123", ""]
"" -> ["", "", "", ""]
The reason I want it to be a one-liner is that I need to put it into vue template string so it needs to be an expression other than a series of statements.
I don't want to create a dedicated function to just convert a single parameter to another form.
I managed to split the string into an array but I don't know how to fill in empty slots with '', here's a simplified snippet:
const creditcard = '12345678123';
// need a one liner
const groups = creditcard.split(/(?<=^(?:.{4})+)/);
console.log(groups);
You could pad the string to minimum 16 characters with spaces, then trim the results
const creditcard = '12345678123';
// need a one liner
const groups = creditcard.padEnd(16, ' ').split(/(?<=^(?:.{4})+)/).map(v => v.trim());
console.log(groups);
Another option is to allocate an array with four elements and populate it with splices from your input:
const input = '111122223333444';
const output = Array(4).fill().map((_, i) => input.split('').splice(i*4, 4).join(''));
console.log(output);
// ["1111", "2222", "3333", "444"]
Use slice you can achieve your goal
Here is the code:
function splitToArray(n) {
const ret = [];
for(let i = 0; i < 16; i += 4) {
ret.push(n.slice(i, i + 4))
}
return ret;
}
console.log(splitToArray(''));
console.log(splitToArray('1234567812345678'));
console.log(splitToArray('12345678123'));
I have big array, which looks like this example:
let array = ['aa-we', 'aa-we__qq', 'aa-we__qw', 'gsPlsOdd', 'bc-po-lp', 'bc-po-lp--ps', 'de', 'de__io', 'de__sl', 'de--xz', 'ccsDdd'];
i want split this array into small arrays by values:
let array = [
['aa-we', 'aa-we__qq', 'aa-we__qw'],
['bc-po-lp', 'bc-po-lp--ps'],
['de', 'de__io', 'de__sl', 'de--xz']
]
// and camelcase strings should be removed
Values in array have syntax like BEM selectors, so if the prefix of different strings is the same, they should be wrapped in a single array.
How can i do this, if possible, without additional libraries?
Thanks for the help or tips!
console.clear()
let data = [
"aa-we",
"aa-we__qq",
"aa-we__qw",
"gsPlsOdd",
"bc-po-lp",
"bc-po-lp--ps",
"de",
"de__io",
"de__sl",
"de--xz",
"ccsDdd",
];
resultO = data.reduce((acc, val, idx) => {
if (val.match(/[A-Z]/)) {return acc;}
const sel = val.replace(/^(.*)(__|--).*$/g, "$1");
acc[sel] = acc[sel] || [];
acc[sel].push(val)
return acc;
}, {})
resultA = Object.values(resultO)
console.log(resultA)
I'd do something like this and then filter out what you don't want.
let array = ['aa-we', 'aa-we__qq', 'aa-we__qw', 'gsPlsOdd', 'bc-po-lp', 'bc-po-lp--ps', 'de', 'de__io', 'de__sl', 'de--xz', 'ccsDdd'];
array = array.filter((a) => !a.match(/[A-Z]/))
let result = groupBy(array, (str)=> str.split(/[-_]/)[0])
console.log(Object.values(result))
function groupBy(arr, condition) {
return arr.reduce((result, current) => {
const key = condition(current);
(result[key] || (result[key] = [])).push(current)
return result
}, {})
}
The algorithm can be as follows:
Create Map<Prefix,ValuesArray>
For each element in array:
Get it's prefix, e.g. "ab", skip element if invalid (e.g. no prefix exist or camel case)
Add to corresponding hashed bucket
Join values from Map into one array
JS has all the primitives to implement this, just take a look at Map/Object for hashing and Array (map/filter/reduce) for processing.