Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

如何在 console 中写代码,统计当前页面出现次数最多的三种标签 #25

Open
Hongbusi opened this issue Jun 30, 2022 · 4 comments
Labels

Comments

@Hongbusi
Copy link
Member

No description provided.

@Hongbusi Hongbusi added handwritten-code today 每日一题。 JS javascript labels Jun 30, 2022
@alexzhang1030
Copy link

先说结论:

Object.entries(Array.from(document.querySelectorAll("*")).map(v => v.tagName).reduce((res, a) => ((res[a] = (res[a] || 0) + 1), res), {})).sort((a, b) => b[1] - a[1]).slice(0, 3)

看不懂?没关系,我们一步一步走,以百度为例吧

1. 拿到所有的标签

其实分为了三步:

// 所有节点
const allNodes = document.querySelectorAll("*");
// 类数组重新构造
const nodeArr = Array.from(allNodes);
// 获取所有的标签
const allTags = nodeArr.map(v => v.tagName);

现在它长这个样子:

image

2. 统计标签出现的次数

下面我们需要使用 reduce 来进行遍历,根据 mdn 对于 reduce 语法的描述

reduce(callbackFn, initialValue)

我们可以通过构造一个对象来统计,key 是 tagName,value 是出现的次数

const tagCountMapping = allTags.reduce((res, a) => ((res[a] = (res[a] || 0) + 1), res), {})

现在它长这样:

image

3. 排序

现在,我们需要通过 mapping 的 value 进行排序,通过 mdn 对于 Object.entries() 的用法描述:

const obj = { foo: 'bar', baz: 42 };
console.log(Object.entries(obj)); // [ ['foo', 'bar'], ['baz', 42] ]

得知,我们可以通过返回的数组的第 1 项值来进行排序

const sortedTag = Object.entries(tagCountMapping).sort((a, b) => b[1] - a[1]);

现在它长这样:

image

4. 截取前 3 位

最终我们得出答案:

const res = sortedTag.slice(0, 3)

image

@guzao
Copy link

guzao commented Jun 30, 2022

function findTheTopThreeElements () {
const elements = document.querySelectorAll('*')
const map = {}
elements.forEach(el => {
map[el.tagName] ? map[el.tagName] += 1 : map[el.tagName] = 1
})
const sortEdArr = Object.keys(map).map(key => {
return [ key, map[key] ]
}).sort((a, b) => b[1] - a[1])
return sortEdArr.splice(0, 3)
}

@Hongbusi
Copy link
Member Author

@guzao 可以看一下 md 语法 - 代码高亮。

@likui628
Copy link

ts版本,根据@alexzhang1030版改编

function topThreeTagName() {
    type ReduceReturnType = {
        [s: string]: number
    };

    Object.entries(
        Array.from(document.querySelectorAll("*"))
            .map(node => node.tagName)
            .reduce<ReduceReturnType>((result, tag) => {
                if (tag in result) {
                    result[tag] += 1;
                } else {
                    result[tag] = 1;
                }
                return result
            }, {}))
        .sort((a, b) => b[1] - a[1])
        .slice(0, 3)
}

@Hongbusi Hongbusi removed the today 每日一题。 label Jul 5, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Development

No branches or pull requests

4 participants