[英]How to check for duplicates in a list and save each email one by line in a file
I have a list like this:我有一个这样的列表:
[
'test@t-online.de',
'kontakt@test.de',
'info@test.de',
'test@gmx.de',
'kontakt@test.de',
]
I want to check for duplicates and save the list in a txt file with one email in each line.我想检查重复项并将列表保存在一个 txt 文件中,每行一个 email。 The final result would be in this case:在这种情况下,最终结果将是:
test@t-online.de
kontakt@test.de
info@test.de
test@gmx.de
fs.writeFileSync('./results/test.txt', list) fs.writeFileSync('./results/test.txt', 列表)
How to do that?怎么做?
You can perform that by performing a loop through the Array if emails and perform a filter to like bellow您可以通过在 Array if emails 中执行循环来执行此操作,并执行过滤器以喜欢下面
let emails = [ 'test@t-online.de', 'kontakt@test.de', 'info@test.de', 'test@gmx.de', 'kontakt@test.de', ]; let result = emails.reduce((accumulator, current) => { if(accumulator.indexOf(current) === -1){ accumulator = accumulator.concat(current); } return accumulator; }, []); console.log(result);
Replace list
with [...(new Set(list))].join('\n')
将list
替换为[...(new Set(list))].join('\n')
new Set()
ensures only duplicates are removed and only unique elements remain. new Set()
确保仅删除重复项并仅保留唯一元素。join('\n')
transforms the Array into a string separated by new-line ( \n
) character. join('\n')
将 Array 转换为由换行符 ( \n
) 分隔的字符串。 const list = [ 'test@t-online.de', 'kontakt@test.de', 'info@test.de', 'test@gmx.de', 'kontakt@test.de', ]; console.log([...(new Set(list))].join('\n'));
for removing duplicated emails:删除重复的电子邮件:
arr = [...new Set(arr)];
for writing写作
var writeStream = fs.createWriteStream('./results/test.txt');
writeStream.on('error', function(e) {
/* handel error here */
});
arr.forEach(email => writeStream.write(email + '\n'));
writeStream.end();
To append data to an existed file Create write stream in append mode将 append 数据写入现有文件在 append 模式下创建写入 stream
var writeStream = fs.createWriteStream('./results/test.txt', { 'flags': 'a', 'encoding': null, 'mode': 0666});
Complete code.完整的代码。 I have used "a"
flag to append the data in same file我已将"a"
标志用于 append 同一文件中的数据
let fs = require('fs');
let data = [
'test@t-online.de',
'kontakt@test.de',
'info@test.de',
'test@gmx.de',
'kontakt@test.de',
];
let stream = fs.createWriteStream("emails.txt", {'flags': 'a'});
stream.once('open', function(fd) {
// this will remove duplicates from the array
const result = data.filter((item, pos) => data.indexOf(item) === pos)
result.forEach(email => stream.write(email + '\n'));
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.