How do I get every single record of an array string substring?
Example:
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)
I tried to add substring:
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
How do I get unique records by comparing the first n characters?
You were close! You just had to use map()
to get the substrings, as the array class has no subString()
method:
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);
As noted elsewhere, shorter isn't necessarily better. reduce()
outperforms creating a new Set. Here it is in one (crammed) line:
const uniq = sourcefiles.reduce((a,s) => { a.includes(s[0]) ? null : a.push(s[0]); return a}, []);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With