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 = [ Set( => a.substring(0,1)))] 

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}, []);

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top