'how to compare and filteredout data with next array special characters string reference in javascript
here is my question how to categorize the array data with the help of other array data elements im confusing how to compare the two array data sets with the common value
how can i access the animal# in referenceBasedValues and how to compare with referenceData elements
const referenceData = ['animal#', 'flower#' , 'Cats#', 'dogs/colorDogs/']
const referenceBasedValues = [{ref : 'animal#cow', value : 'Cow'},
{ref : 'animal#pig', value : 'Pig'},
{ref : 'animal#hourse', value : 'Hourse'},
{ref : 'flower#rose', value : 'Rose'},
{ref : 'flower#leafRose', value : 'Leaf Rose'},
{ref : 'Cats#bigcat', value : 'Big cat'},
{ref : 'Cats#smallcat', value : 'Small Cat'},
{ref : 'dogs/colorDogs/whiteDog', value : 'White dog'},
{ref : 'dogs/colorDogs/BlackDog', value : 'Black dog'},]
Im expecting the output like this
const finalData = [{reference : 'animal#' , values :['Cow' , 'Pig' ,'Hourse']},
{reference : 'flower#' , values :['Rose' , 'Leaf Rose' ,'Hourse']},
{reference : 'Cats#' , values :['Big cat' , 'Small Cat']},
{reference : 'dogs/colorDogs/' , values :['White dog','Black dog']}
]
im able to accesing animal#, flower#, Cats# with substring(0 , referenceData[i].reference.lastIndexOf("#"))
but im not able to accessing dogs/colorDogs/ word in array while filtering
If any one give answer for this one so appreciatable
Solution 1:[1]
// v1
const finalData = referenceData.map(reference => {
const re = new RegExp('^' + reference);
const values = referenceBasedValues.filter(base => re.test(base.ref)).map(base => base.value);
return {
reference,
values,
};
});
// v2
const re = new RegExp(`^(${referenceData.join('|')})`);
const finalData = Object.entries(referenceBasedValues.reduce((obj, { ref, value }) => {
const match = re.exec(ref);
if (match) {
let key = match[0];
obj[key] ??= [];
obj[key].push(value);
}
return obj;
}, {})).map(([reference, values]) => ({ reference, values }));
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | rookie |
