PL
JavaScript - usuwanie zduplikowanych linii
0
points
W tym artykule chcielibyśmy pokazać, jak w JavaScript usunąć zduplikowane linie z tekstu.
Szybkie rozwiązanie:
// ONLINE-RUNNER:browser;
const newLineExpression = /\r\n|\n\r|\n|\r/g;
const removeDuplicatedLines = (text) => {
let result = '';
const blocker = {}; // zapobiega duplikowaniu linii
const lines = text.split(newLineExpression);
for (const line of lines) {
if (blocker.hasOwnProperty(line)) {
continue;
}
blocker[line] = true;
result += line + '\n';
}
return result;
};
// Przykład użycia:
const text = `a
b
b
a
a
c
c`;
console.log(removeDuplicatedLines(text)); // a
// b
// c
Przykład oparty o funkcję filter()
To podejście wykorzystuje funkcyjny wzorzec programowania.
// ONLINE-RUNNER:browser;
const newLineExpression = /\r\n|\n\r|\n|\r/g;
const removeDuplicatedLines = (text) => {
return text.split(newLineExpression)
.filter((item, index, array) => array.indexOf(item) === index)
.join('\n');
};
// Przykład użycia:
const text = `a
b
b
a
a
c
c`;
console.log(removeDuplicatedLines(text)); // a
// b
// c
Przykład oparty o funkcję reduce()
To podejście ma na celu pokazanie, że można uzyskać ten sam efekt za pomocą metody reduce()
.
// ONLINE-RUNNER:browser;
const newLineExpression = /\r\n|\n\r|\n|\r/g;
const removeDuplicatedLines = (text) => {
const blocker = {}; // zapobieka duplikowaniu linii
return text.split(newLineExpression)
.reduce((result, line) => {
if (blocker.hasOwnProperty(line)) {
return result;
}
blocker[line] = true;
return result + line + '\n';
}, '');
};
// Przykład użycia:
const text = `a
b
b
a
a
c
c`;
console.log(removeDuplicatedLines(text)); // a
// b
// c