Languages
[Edit]
PL

JavaScript - usuwanie zduplikowanych linii

0 points
Created by:
GamerGoals22
364

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

Powiązane posty

Zobacz też

Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join