Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to build a string from javascript array

I’m using javascript, and I have a function which generate for me an array like this :

[
 "perfumers/any(perfumer: perfumer/name eq 'Test1')",
 "perfumers/any(perfumer: perfumer/name eq 'Test2')",
 "line_unit/name eq 'EDC'",
 "line_unit/name eq 'EDT'",
 "line_unit/name eq 'EDM'",
 "line_unit/name eq 'EDK'",
 "color/name eq 'RED'",
 "color/name eq 'BLUE'",
]

and I want from this array to have string like this :

"(perfumers/any(perfumer: perfumer/name eq 'Test1') or perfumers/any(perfumer: perfumer/name eq 'Test2') )

and (line_unit/name eq 'EDC' or line_unit/name eq 'EDT' or line_unit/name eq 'EDM' or line_unit/name eq 'EDK)

and (color/name eq 'RED' or color/name eq 'BLUE')"

Do you have any idea please how can do that using javascript ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

you can do something like this

const data = [
 "perfumers/any(perfumer: perfumer/name eq 'Test1')",
 "perfumers/any(perfumer: perfumer/name eq 'Test2')",
 "line_unit/name eq 'EDC'",
 "line_unit/name eq 'EDT'",
 "line_unit/name eq 'EDM'",
 "line_unit/name eq 'EDK'",
 "color/name eq 'RED'",
 "color/name eq 'BLUE'",
]

const transform = data => Object.values(data.reduce((res, item) => {
  const [prefix, ...rest] = item.split(' ')
  const existing = res[prefix] || []
  return {
    ...res,
    [prefix]: [...existing, item]
  }
}, {})).map(items => `( ${items.join(' or ')} )`).join(' and ')

console.log(transform(data))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading