gpt4 book ai didi

javascript - 如何通过比较前 n 个字符来获得唯一记录?

转载 作者:行者123 更新时间:2023-12-03 06:54:08 24 4
gpt4 key购买 nike

如何获取数组字符串子字符串的每条记录?
例子:

sourcefiles = ['a.pdf', 'a_ok.pdf', 'a.csv', 'b_ok.csv', 'b.csv', 'c.pdf']
var uniq = [ ...new Set(sourcefiles)]; //I want the output to be: a, b, c
console.log(uniq)

我尝试添加子字符串:

sourcefiles = ['a.pdf', 'a_ok.pdf', 'a.csv', 'b_ok.csv', 'b.csv', 'c.pdf']
var uniq = [ ...new Set(sourcefiles.substring(0,1))];
console.log(uniq)
VM116792:2 Uncaught TypeError: sourcefiles.substring is not a function
at <anonymous>:2:37
如何通过比较前 n 个字符来获得唯一记录?

最佳答案

你很亲近!你只需要使用 map()获取子字符串,因为数组类没有 subString()方法:

const sourcefiles = ['a.pdf', 'a_ok.pdf', 'a.csv', 'b_ok.csv', 'b.csv', 'c.pdf'];
const uniq = [...new Set(sourcefiles.map(a => a.substring(0,1)))]
console.log(uniq);

正如其他地方所指出的,更短并不一定更好。 reduce()优于创建新集合。这是一个(拥挤的)行:
const uniq = sourcefiles.reduce((a,s) => { a.includes(s[0]) ? null : a.push(s[0]); return a}, []);

关于javascript - 如何通过比较前 n 个字符来获得唯一记录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64592009/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com