skip to Main Content

I am trying to get the non repeating values from the 2 inputs.
Ex: If I type some names in the first input: George, Michael, John and in 2nd input: John, Robert, Michael.
should return in the 3 input: George, Robert.

# const resultElement = document.getElementById('ResultField');
      const text1Element = document.getElementById('old');
      const text2Element = document.getElementById('new');

      function myFunction() {
        const x = text1Element.value;
        const y = text2Element.value;

        //split the textareas by newlines
        const xArr = x.split('n');
        const yArr = y.split('n');

        const result = xArr
          .map((line, index) => {
            return line + ' ' + yArr[index];
          }, '')
          .join('n');

        const removeDuplicates = result.split(/s/g).filter((word, i, arr) => arr.indexOf(word) !== i);

        resultElement.value = removeDuplicates;
      }

using this line I get the duplicates. ex: Michael, John
const removeDuplicates = result.split(/s/g).filter((word, i, arr) => arr.indexOf(word) !== i);

if I change "!" to "=" I get the combine input. ex: George, Michael, John, Robert
const removeDuplicates = result.split(/s/g).filter((word, i, arr) => arr.indexOf(word) === i);

Many thanks.

2

Answers


  1. You are looking for the symmetric differences.

    // ...
    
    const xArr = x.split('n');
    const yArr = y.split('n');
    
    const diff = xArr.filter(x => !yArr.includes(x)).concat(yArr.filter(y => !xArr.includes(y)));
    
    resultElement.value = diff.join('n')
    
    Login or Signup to reply.
  2. You could keep a count of the words in a concatenated list, then filter out any word that appeared more than once.

    const xArr = x.split('n');
    const yArr = y.split('n');
    const both = xArr.concat(yArr);
    
    const counts = both.reduce((aggCounts, name) => {
      aggCounts[name] = (aggCounts[name] || 0) + 1;
      return aggCounts;
    }, {});
    
    resultElement.value = both.filter(name => counts[name] < 2).join('n');
    

    This has an O(n) runtime, with O(n) space.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search