2

I am comparing two arrays for matched items but I need to make them case insensitive.

here is the code: credit for this code to @PatrickRoberts here

const words = ['word1', 'word2', 'word3']
const texts = [
    {name: 'blah', description: 'word4'},
    {name: 'blah2', description: 'word1'},
    {name: 'blah3', description: 'word5'}
]

console.log(
  texts.some(
    ({ description }) => words.includes(description)
  )
)

I was able to get the second part to lower case by doing words.includes(description.toLowerCase()) but I don't know how to handle the first part: texts.some(({ description }) I should mention I have tried adding toLowerCase() to { description } like this: { description.toLowerCase() } but this does not work

any help is greatly appreciated

Patrick Roberts
  • 49,224
  • 10
  • 102
  • 153
Jason
  • 1,091
  • 4
  • 19
  • 40

3 Answers3

3

Switch either to the function some or function find or function findIndex.

const words = ['Word1', 'word2', 'word3']
const texts = [{    name: 'blah',    description: 'word4'  },  {    name: 'blah2',    description: 'word1'  },  {    name: 'blah3',    description: 'word5'  }];

console.log(texts.some(({description}) => words.some((w) => w.toLowerCase() === description.toLowerCase())));
Ele
  • 33,468
  • 7
  • 37
  • 75
  • I will accept your answer as soon as stackoverflow lets me – Jason Mar 01 '19 at 23:21
  • Calling `description.toLowerCase()` in the inner arrow function is unnecessarily repeating a large amount of work that could be done in the outer arrow function instead. – Patrick Roberts Mar 01 '19 at 23:42
2

No, it's not possible to change it during the destructuring process - this answer explains why.

It's much easier to check by using some instead of includes:

const words = ['word1', 'word2', 'word3']
const texts = [{
    name: 'blah',
    description: 'word4'
  },
  {
    name: 'blah2',
    description: 'word1'
  },
  {
    name: 'blah3',
    description: 'word5'
  }
]

console.log(
  texts.some(
    ({
      description
    }) => words.some(word => word.toLowerCase == description.toLowerCase())
  )
)
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
0
  1. Use JSON.stringify to convert your objects into strings
  2. Apply .toLowerCase to the obtained strings so that everything (including all values) becomes lowercase
  3. Convert back into an object or array using JSON.parse
  4. Apply the rest of the matching logic with Array.some and Array.includes

const words = ['WORD1', 'WORD2', 'WORD3'];
const texts = [
    {name: 'blah', description: 'word4'},
    {name: 'blah2', description: 'word1'},
    {name: 'blah3', description: 'word5'}
];

const lower = x => JSON.parse(JSON.stringify(x).toLowerCase());
const [lowerWords, lowerTexts] = [words, texts].map(lower);

console.log(
  lowerTexts.some(
    ({ description }) => lowerWords.includes(description)
  )
)
molamk
  • 4,076
  • 1
  • 13
  • 22