Reputation: 95
I have several strings, some contain just a phrase, and others contain phrases separated by commas. How can I split each of the strings and then save them into an array?
Example strings:
a = "Shipping, Receiving"
b = "Research and development, Building services"
c = "Cafeteria"
d = "Receiving, Building services, Cafeteria"
I need the array to contain:
Shipping
Receiving
Research and development
Building services
Cafeteria
I'm pulling the data from a web page that is stored in divs with the class "audience".
const audience = document.querySelectorAll('.audience');
const allcats = [];
audience.forEach((element) => {
allcats.push(element.textContent.trim());
});
I need to know how to step through these and add them to the array.
Upvotes: 0
Views: 83
Reputation: 63587
const a = 'Shipping, Receiving';
const b = 'Research and development, Building services';
const c = 'Cafeteria';
const d = 'Receiving, Building services, Cafeteria';
// Combine the strings into an array. For
// each split the string using a regex that
// looks for a comma followed by an optional space
// and flatten the remaining nested array with
// `flatMap`
const arr = [a, b, c, d].flatMap(str => {
return str.split(/,\s?/);
});
// Create a new Set from the array to dedupe the
// elements, and then convert it back into an array
// for viewing
// create an array from the
console.log([...new Set(arr)]);
Additional information
Upvotes: 1
Reputation: 29
You could do something like this.
let uniquePhrases = [];
let concatStr = a + ',' + b + ',' + c + ',' + d
let split = concatStr.split(',')
split.map( el => {
let trimmed = (el.trim())
if(!uniquePhrases.includes(trimmed)) {
uniquePhrases.push(trimmed)
} else { return }
})
In summation:
uniquePhrases
Upvotes: 0
Reputation: 199
Using your example here's what you could do to get the unique set of words separated by a comma
const a = "Shipping, Receiving"
const b = "Research and development, Building services"
const c = "Cafeteria"
const d = "Receiving, Building services, Cafeteria"
// array of arrays
const preprocess = [a, b, c, d].map(item => item.split(',').map(i => i.trim()))
console.log({preprocess})
// flatten array -> contains duplicates
const processed = preprocess.reduce((prev, curr) => ([...prev, ...curr]))
// In ES2019 could use [].flat(preprocess)
console.log({processed})
const unique = new Set(processed)
console.log({result: [...unique]})
Upvotes: 0
Reputation: 15867
My answer loops through your audience divs and splits the content then loops through that content and checks to see if its in the array. If its not in the array, then it is pushed to the array.
const audience = document.querySelectorAll('.audience');
const allcats = [];
audience.forEach((element) => {
element.textContent.split(",").forEach(function(str){
if(allcats.includes(str.trim()) === false){
allcats.push(str.trim());
}
});
});
console.log(allcats)
<div class="audience">Shipping, Receiving</div>
<div class="audience">Research and development, Building services</div>
<div class="audience">Cafeteria</div>
<div class="audience">Receiving, Building services, Cafeteria</div>
Upvotes: 1
Reputation: 44
const a = "Shipping, Receiving"
const b = "Research and development, Building services"
const c = "Cafeteria"
const d = "Receiving, Building services, Cafeteria"
const arr = Array.from(new Set(
[
...a.split(',').map(el => el.trim()),
...b.split(',').map(el => el.trim()),
...c.split(',').map(el => el.trim()),
...d.split(',').map(el => el.trim()),
]
))
console.log(arr);
Upvotes: 0
Reputation: 64
Use the split() method, for example:
const str = 'Hear about the new restaurant called Karma, There’s no menu: You get what you deserve';
// explode by every char
str.split('') // ['H', 'e', 'a', 'r', ' ', 'a', 'b', 'o', 'u', 't', ' ', 't', 'h', 'e', ' ', 'n', 'e', 'w', ' ', 'r', 'e', 's', 't', 'a', 'u', 'r', 'a', 'n', 't', ' ', 'c', 'a', 'l', 'l', 'e', 'd', ' ', 'K', 'a', 'r', 'm', 'a', ',', ' ', 'T', 'h', 'e', 'r', 'e', '’', 's', ' ', 'n', 'o', ' ', 'm', 'e', 'n', 'u', ':', ' ', 'Y', 'o', 'u', ' ', 'g', 'e', 't', ' ', 'w', 'h', 'a', 't', ' ', 'y', 'o', 'u', ' ', 'd', 'e', 's', 'e', 'r', 'v', 'e']
// explode by space
str.split(' ') // ['Hear', 'about', 'the', 'new', 'restaurant', 'called', 'Karma,', 'There’s', 'no', 'menu:', 'You', 'get', 'what', 'you', 'deserve']
// explode by comma
str.split(',') // ['Hear about the new restaurant called Karma', ' There’s no menu: You get what you deserve']
Upvotes: 0