Skip to content Skip to sidebar Skip to footer

Merging The Duplicate In String And Append It With Comma Gives Wrong Output

Supposed i have a function that merge the duplicate in string and append the value with comma let check = 'test_name=sdf&test_name=dfgdfg&test_last_name=dfg'; let final =

Solution 1:

The point at which your problem happens is because:

test_name=,&test_last_name=dfg // now there is a comma

test_name maps to ['', '']

and in

test_name=,eqwe&test_last_name=dfg

test_name maps to ['', 'eqwe'].

Which makes sense, you're not stripping any values yet.

Note how in your second example, you still don't want the comma in there, even though there are no duplicate values.

Skip empty strings

Instead of deduplicating, one thing you can do is filter out all empty strings from your list, either by:

  1. In the reduce method, Skipping r.set if v === ''
  2. Using v[1].filter(val => val !== '') in your string formatter

Deduplicate?

As I mentioned, from the way you describe your specs, you'll always want to discard empty strings.

If you still want to dedup on top of that, consider:

  1. Putting a Set as the value of a map instead of a list. It deduplicates for you.
  2. Writing your own unique function:
/** Returns unique copy of arr in the same order as the elements in arr */functionunique(arr) {
  const set = newSet();

  for (const item of arr) {
    set.add(item);
  }

  returnArray.from(set.values());
}

Solution 2:

Here's one way to do it

const check = 'test_name=sdf&test_name=dfgdfg&test_last_name=dfg';

//  bag will hold our URLencded string in structured formconst bag = newMap();

check.split('&').forEach(kv => {
    let [k,v] = kv.split('=');
    if (bag.has(k)) {
        // if key exists, merge with other value(s)
        bag.set( k, [v].concat(bag.get(k)));
    } else {
        bag.set(k,[v]);
    }
});

// iterate over key+value pairs, joining with '&' and '='let final = Array.from(bag).map(([k,v]) => {
   // iterate over values, joining with ','let token = [k,v.join(',')].join('=');
   return token;
}).join('&');

console.log(final); // test_name=sdf,dfgdfg&test_last_name=dfg

Post a Comment for "Merging The Duplicate In String And Append It With Comma Gives Wrong Output"