How can I split an array into multiple arrays and store each of these new arrays as their own variable?
Example
let arr: string[] = [
"",
"Names",
"jack",
"paul",
"sarah",
"",
"Genders",
"m",
"m",
"m",
"f",
"",
"Cars",
"range rover",
"bmw",
"mercedes",
"dodge",
];
How can I split this array with TypeScript to new arrays like (before every new variable there is an empty string in the array (before Names, Genders and Cars):
names: string[] = ["Names", "jack", "paul", "sarah",]
genders: string[] = ["m","m","m","f"]
cars: string[] = ["Cars", "range rover", "bmw", "mercedes", "dodge",]
CodePudding user response:
You can use the reduce()
array method to walk through arr
and accumulate your output array of arrays of strings:
const result = arr.reduce<string[][]>(
(a, s) => !s ? [...a, []] : [...a.slice(0, -1), [...a[a.length - 1], s]]
, []);
In the above, a
is the accumulator which stores the output so far, and s
is the current string element from arr
. The idea is that s
is an empty string you add a new empty array to the end of a
, and when s
is non-empty you put it at the end of the last array in s
.
I've gone the route of treating everything as immutable, using the slice()
array method and destructuring assignment and array spread to manipulate arrays. The value [...a, []]
has the same elements as a
with a new empty array at the end. The value [...a.slice(0, -1), [...a[a.length - 1], s]]
has the same elements as a
except the last one has s
added to the end. (a.slice(0, -1)
uses the slice()
array method to get a copy of a
without the last element, and a[a.length-1]
is that last element.)
Let's test it:
console.log(result);
/* [["Names", "jack", "paul", "sarah"],
["Genders", "m", "m", "m", "f"],
["Cars", "range rover", "bmw", "mercedes", "dodge"]]*/
Looks good, and you can assign those arrays to separate variables if you want:
const [names, genders, cars] = result;
console.log({ names, genders, cars });
/* {
"names": [
"Names",
"jack",
"paul",
"sarah"
],
"genders": [
"Genders",
"m",
"m",
"m",
"f"
],
"cars": [
"Cars",
"range rover",
"bmw",
"mercedes",
"dodge"
]
} */
Looks like what you wanted.
CodePudding user response:
Use JS Object for storing this kind of data structure:
type myObject = {
"Names": ["jack", "paul", "sarah"],
"Genders": ["m","m","m","f"],
"Cars": ["range rover", "bmw", "mercedes", "dodge"]
}
then you access like this:
myObject.Names => ["jack", "paul", "sarah"]