Reputation: 57
I have a question, I have a text.file that contains a string, this code right now prints out words and lets me know how many same words have been used.. Is there a way that I could put the words in an alphabetical order in the Node.js environment.
Code:
const { readFile, readFileSync } = require('fs');
let file = 'C:\\Users\\eeroj\\source\\repos\\Nodejs\\pish\\pish\\TextFile2.txt';
let words = "";
function countRepeatedWords(sentence) {
let words = sentence.split(" ");
let wordMap = {};
for (let i = 0; i < words.length; i++) {
let currentWordCount = wordMap[words[i]];
let count = currentWordCount ? currentWordCount : 0;
wordMap[words[i]] = count + 1;
}
return wordMap;
}
words = readFileSync(file).toString();
console.log(countRepeatedWords(words));
Upvotes: 1
Views: 246
Reputation: 30685
You can use Object.entries()
to create a list of your object entries, then sort them by key using Array.sort()
, then create your sorted map using Object.fromEntries()
:
const { readFileSync } = require('fs');
let file = 'C:\\Users\\eeroj\\source\\repos\\Nodejs\\pish\\pish\\TextFile2.txt';
function countRepeatedWords(sentence) {
const wordMap = sentence.toLowerCase().split(" ").reduce((acc,cur) => {
acc[cur] = (acc[cur] || 0) + 1;
return acc;
}, {});
// Sort the map alphabetically...
const sortedEntries = Object.entries(wordMap).sort(([a,],[b,]) => a.localeCompare(b));
const sortedWordMap = Object.fromEntries(sortedEntries);
return sortedWordMap;
}
const words = readFileSync(file).toString();
console.log(countRepeatedWords(words));
And a snippet to demonstrate:
function countRepeatedWords(sentence) {
const wordMap = sentence.toLowerCase().split(" ").reduce((acc,cur) => {
acc[cur] = (acc[cur] || 0) + 1;
return acc;
}, {});
// Sort the map alphabetically...
const sortedEntries = Object.entries(wordMap).sort(([a,],[b,]) => a.localeCompare(b));
const sortedWordMap = Object.fromEntries(sortedEntries);
return sortedWordMap;
}
const words = `What a piece of work is a man How Noble in reason How infinite in faculty In form and moving how express and admirable In Action how like an Angel in apprehension how like a God The beauty of the world the paragon of animals and yet to me what is this quintessence of dust Man delights not me nor woman neither though by your smiling you seem to say so` ;
console.log(countRepeatedWords(words));
Upvotes: 1
Reputation: 205
wordMap.sort((a,b) => a.word - b.word);
wordMap.sort();
Upvotes: 0