Home > Net >  Using JavaScript get addition of the two strings which having same characters occurs and returns rem
Using JavaScript get addition of the two strings which having same characters occurs and returns rem

Time:09-26

I need to make addition of the two strings which having number and character combinations. Matched characters attached numbers should get add and other string should remains same.

let string1 = '2B 3P 7R 1E';
let string2 = '3B 4A 5P';
let concatStrings = string1.concat(' ' string2);
let splitString = concatStrings.split(' ');
let newArray = [];
let tempArray = []
splitString.map(x1 => {
    let combData = x1.match(/(\d )(\w )/);
    let numbersOnly = combData[1];
    let lettersOnly = combData[2];

    if(!tempArray.includes(lettersOnly)){
        tempArray.push(lettersOnly);
    }
    
    newArray.push({num:numbersOnly,char:lettersOnly})

});

const res = Object.values(newArray.reduce((a, { num, char }) => {
    a[num] = a[num] || { num, char: new Set() };
    a[num].char.add(char);
    return a;
  }, {})).map(({ num, char }) => ({ num, char: [...char].join(",")}));
  
  console.log(res);
  
  //Output should print 5B 8P 4A 7R 1E
  //sequence should not matter

CodePudding user response:

I'm not sure why you're grouping the pairs by value there, you want to combine them by key.

As the whole snippet was, frankly, kindof a mess, I rewrote your logic completely. You can now pass any number of strings to the addStrings function.

function addStrings(...strings) {
  // We're going to store our summed values in here.
  const summed = {};

  // For every input string
  strings.forEach(str => {
    // Split the string up into separate key/value pairs
    str.split(' ')
      .forEach((pair) => {
        // Extract the key and the value for each pair
        const [count, key] = pair.split('');
        // And add that to the summed value, making sure to parse the count to a integer.
        summed[key] = (summed[key] || 0)   parseInt(count, 10);
      });
  });

  // Now convert all summed entries into pairs, and join them into a string.
  return Object.entries(summed)
    .map(([k, v]) => v   k)
    .join(' ');
}

console.log(addStrings('2B 3P 7R 1E', '3B 4A 5P'));

CodePudding user response:

I think your idea, to first concatenate the strings and to use a regex for extracting the values and names, was good.

You could then split the task into parts. Create a function to:

  • decode the string into pairs
  • combine the pairs into an object, grouped by name, and related sums
  • encode that object into a string

Code:

const toPairs = (str) => Array.from(str.matchAll(/(\d )([^ ] )/g));
const toString = (obj) => Object.entries(obj).map(([k, v]) => v   k).join(" ");
const toObject = (pairs) => pairs.reduce((acc, [, v, k]) => 
    Object.assign(acc, { [k]: (acc[k] ?? 0)    v }), {});  

// demo
let string1 = '2B 3P 7R 1E';
let string2 = '3B 4A 5P';
let result = toString(toObject(toPairs([string1, string2].join(" "))));

console.log(result);

  • Related