JavaScript嵌套Map唯一元素计数实现及数据结构选型咨询
Step 1: Transform the Data
Here's a straightforward way to convert your original data into the desired unique element count format. The code uses basic JavaScript object/array methods and Map for frequency counting (a plain object works too):
// Your original data const wordData = { 'fight': ['02222', '02222', '02222', '02222', '20000'], 'eight': ['02222', '02222', '02222', '02222', '10000'], 'right': ['02222', '02222', '02222', '02222', '10000'], 'sight': ['02222', '02222', '02222', '02222', '10000'], 'night': ['02222', '02222', '02222', '02222', '10000'], 'ferns': ['20000', '01000', '00100', '00001', '00010'] }; // Transform to count unique elements const countResult = [Object.fromEntries( Object.entries(wordData).map(([word, strArray]) => { // Track frequency of each string in the array const frequencyMap = new Map(); strArray.forEach(str => { frequencyMap.set(str, (frequencyMap.get(str) || 0) + 1); }); // Extract counts, sort them ascending, and return the word-count pair const counts = Array.from(frequencyMap.values()).sort((a, b) => a - b); return [word, counts]; }) )]; console.log(countResult);
Breakdown:
Object.entries(wordData)converts your original object into an array of[key, value]pairs for easy iteration.- For each word's string array:
- A
Maptracks how many times each string appears. Array.from(frequencyMap.values())pulls out the count numbers from the map.sort((a, b) => a - b)sorts counts in ascending order (matching your example output).
- A
Object.fromEntries()converts the processed[word, counts]pairs back into an object.- The final object is wrapped in an array to match your desired output structure.
Step 2: Data Structure Advice
Original Data Storage
Your current object is perfectly suitable for storing word-to-string-array mappings. If you ever need to:
- Handle keys with special characters (unlikely for Wordle words), a
Mapis more robust (object keys are limited to valid identifier strings). - Guarantee insertion-order iteration,
Mappreserves order consistently (modern browsers mostly preserve object key order, butMapis more reliable for this).
Frequency Counting
Using Map for frequency counting is clean, but a plain object works just as well here (since your string values are valid object keys). Here's an alternative using an object:
const frequencyObj = {}; strArray.forEach(str => { frequencyObj[str] = (frequencyObj[str] || 0) + 1; }); const counts = Object.values(frequencyObj).sort((a, b) => a - b);
Output Format
Your desired output wraps the result object in an array. If you only need to look up counts by word, keeping it as a standalone object (without the array wrapper) would be more practical for future operations (e.g., countResult.fight instead of countResult[0].fight). Stick with the array structure only if your app's data flow requires it.
内容的提问来源于stack exchange,提问作者blackened

