javascript中不区分大小写的数组比较

问题描述 投票:0回答:3

我正在比较匹配项目的两个数组,但我需要使它们不区分大小写。

这是代码:这个代码归功于@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)
  )
)

我能够通过做words.includes(description.toLowerCase())得到第二部分小写,但我不知道如何处理第一部分:texts.some(({ description })我应该提到我已经尝试添加toLowerCase()到{description}像这样:{ description.toLowerCase() }但这不工作

任何帮助是极大的赞赏

javascript arrays array-filter
3个回答
2
投票

切换到函数some或函数find或函数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())));

0
投票

不,在解构过程中不可能改变它 - this answer解释了原因。

使用some而不是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())
  )
)

0
投票
  1. 使用JSON.stringify将对象转换为字符串
  2. .toLowerCase应用于获取的字符串,以便所有内容(包括所有值)都变为小写
  3. 使用JSON.parse转换回对象或数组
  4. 将其余的匹配逻辑应用于Array.someArray.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)
  )
)
© www.soinside.com 2019 - 2024. All rights reserved.