Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get unique records by comparing the first n characters?

Tags:

javascript

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?

like image 322
Cristiano Felipe Avatar asked Oct 29 '20 13:10

Cristiano Felipe


1 Answers

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}, []);
like image 60
chad_ Avatar answered Sep 23 '22 12:09

chad_