-6

I need find and delete all anagrams from an array. All my attempts give ["bac","art"], but I need ["art"]

const deleteAnagrams = (arr) => {
    let obj = {};
  
  for (let i = 0; i < arr.length; i++) {
    let sorted = arr[i].toLowerCase().split("").sort().join("");
    obj[sorted] = arr[i];
  }

  return Object.values(obj);
};

console.log(deleteAnagrams(['cab', 'bac', 'art']))

aftab
  • 11
  • 2

1 Answers1

0

You are actually storing unique strings with the last occurence to the object. But you need to remove duplicates and keep only singel occurences of same sorted strings.

To get the result, you need to filter the values.

const deleteAnagrams = array => {
    const object = {};
  
    for (const word of array) {
        let sorted = word.toLowerCase().split("").sort().join("");
        object[sorted] = sorted in object ? undefined : word;
    }

    return Object.values(object).filter(Boolean);
};

console.log(deleteAnagrams(['cab', 'bac', 'art']));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392