【问题标题】:case insensitive array comparison in javascriptjavascript中不区分大小写的数组比较
【发布时间】:2019-03-01 23:13:06
【问题描述】:

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

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


    【解决方案1】:

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

    【讨论】:

    • 只要 stackoverflow 允许我,我就会接受你的回答
    • 在内部箭头函数中调用 description.toLowerCase() 会不必要地重复大量可以在外部箭头函数中完成的工作。
    【解决方案2】:

    不,在解构过程中无法更改它 - 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())
      )
    )

    【讨论】:

    • 这和Ele's answer有什么不同?
    • 对不起@PatrickRoberts,自从我在移动设备上,我没有意识到 Ele 已经发布了。
    【解决方案3】:
    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)
      )
    )

    【讨论】:

    • 是的,你是对的@Ele。感谢您的关注,我会进行编辑
    • 这假定description 单词也总是小写。这不一定是真的。
    • @PatrickRoberts 对,description 可能不是小写字母。我会进行编辑。感谢您了解
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-18
    • 2013-03-11
    • 2011-05-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多