Home > Back-end >  Nodejs find multiple value
Nodejs find multiple value

Time:07-26

I have two lists:

lista_source: 'B10L-A2,AABan38711$B10L-A2,AABan38811$B12A-A,AABan38912$B14-A2,AABan39314$B16B-A,AABan39616$B12A-A,AABan39818$B16L-B,AABan39919$B16L-B,AABan40019$B12A-A,AABan41112'

second_list: 'B10L-A2,B12A-A,B16L-B'

As a result I would like to get the following list (or similar one):

result = [B10L-A2:AABan38711,AABan38811],[B12A-A:AABan38912,AABan41112,AABan39818],[B16L-B:AABan39919,AABan40019]

In short, I'm looking for multiple values for the 2nd lists items.

I tried the filter function and write it to csv file but does not really work.

const first_list_object= first_list.split('$');
const second_list_object= second_list.split(',');

for (let i = 0; i < second_list_object.length; i  ) {
  
  let results= first_list_object.filter(x => x.includes(second_list_object[i]));
  console.log(results);

  writer = csvWriter({ sendHeaders: false });
  writer.pipe(fs.createWriteStream(__dirname   '/lista.csv', { flags: 'a' }));
  
  writer.write({
    results
  });


}

How should I solve it? Is there any better solution than filter?

CodePudding user response:

A javascript object as output. If you need, I can convert this to .csv too.

const lista_source =  'B10L-A2,AABan38711$B10L-A2,AABan38811$B12A-A,AABan38912$B14-A2,AABan39314$B16B-A,AABan39616$B12A-A,AABan39818$B16L-B,AABan39919$B16L-B,AABan40019$B12A-A,AABan41112'
const second_list = 'B10L-A2,B12A-A,B16L-B'

// convert data to arrays
const source = lista_source.split(",")
const second = second_list.split(",")

// filter out source list items (into seperate object value) for each second list item
const res = second.reduce((obj, sec_key) => {
    // get item, if string is not exact key name and string includes key name
    const filtered = source.filter(key => key !== sec_key && key.includes(sec_key))
    return ({...obj, [sec_key]: filtered })
}, {})

console.log(res)

CodePudding user response:

Assuming that structure of the strings are gonna be like in question, I wrote same basic regex to split on and then add them accordingly to object. See if that's what you want.

Edit: After rereading your question, I realized that comma actually doesn't separate values in your string but dolar sign instead (kinda weird but ok). I also added an if to take only values present in second list.

const lista_source = 'B10L-A2,AABan38711$B10L-A2,AABan38811$B12A-A,AABan38912$B14-A2,AABan39314$B16B-A,AABan39616$B12A-A,AABan39818$B16L-B,AABan39919$B16L-B,AABan40019$B12A-A,AABan41112'
const second_list = 'B10L-A2,B12A-A,B16L-B'.split(',')

const array = lista_source.match(/B[0-9]{2}[A-Z]-[A-Z][0-9]?,[A-Za-z0-9_]{10}/g)
let result = {}

for (let value of array) {
  let [key, s] = value.split(',')

  // only take keys form contained in second list
  if(!second_list.includes(key)){
continue
  }

  key in result ? result[key] = [s, ...result[key]] : result[key] = [s]
}

console.log(result)

  • Related