gpt4 book ai didi

javascript - 我怎样才能以更有效的方式减少它

转载 作者:行者123 更新时间:2023-12-02 22:28:30 24 4
gpt4 key购买 nike

要求 - 在 UI( Angular 6)中显示如下内容列表,其中包括首先按最大计数排序,如果计数相同,则按字母顺序 (A-Z) 排列它们。

Aditya (4) // numbers are clickable links
Bankesh (3)
Bikaji (3)
Zebra (1)

我有一个数据如下:


thingsNames = [];


const data = [
{loc: 'abs', things : ['Aditya','Bankesh'] },
{loc: 'abc', things: ['Aditya','Bikaji'] },
{loc: 'abz', things: ['Aditya','Bikaji'] },
{loc: 'dsd', things: ['Aditya','Bankesh']},
{loc: 'fre', things: ['Bankesh','Bikaji','Zebra'] }
]

我是如何实现上述要求的:

const names = [];
_.forEach(data, (item) => {
_.forEach(item.things, (thing) => {
names.push(thing); //this will be in the same array.here the output is names = ['Aditya', 'Aditya',Aditya','Aditya','Bankesh','Bankesh','Bankesh','Bikaji','Bikaji','Bikaji','Zebra' ]; // it is //not arranged i just wrote it likewise.

const toString = ([name, count]) => `${name}(${count})`;
const entry = _.entries(_.countBy(names));
const finalResult = _.orderBy(entry, [1, 0], ['desc', 'asc']); // sorting i have achieved here
const result = _.map(finalResult, toString); // this create everytime a new array.
this.thingsNames = result;
});
});

上面代码的o/p就像数组中的Aditya(4)...,我在UI中显示如下:


<div *ngFor = "let thingsName of thingsNames">

{{thingsName}}

</div>
                   // shows as 
// Aditya(4)
// Bankesh(3)
// Bikaji(3)
// Zeebra(1)

我面临的问题是,如果数据包含100行那么它将浪费系统中太多的内存,这不是一个好的做法,其次,我希望计数和名称作为不同的键,以便我可以使计数可点击。

我怎样才能实现它们。

最佳答案

您无法避免重新排序条目的需要,但您可以使用 _.flatMap() 而不是嵌套的 _.forEach() 调用来重构代码,并跳过末尾多余的 _.map():

const data = [ 
{loc: 'abs', things : ['Aditya','Bankesh'] },
{loc: 'abc', things: ['Aditya','Bikaji'] },
{loc: 'abz', things: ['Aditya','Bikaji'] },
{loc: 'dsd', things: ['Aditya','Bankesh']},
{loc: 'fre', things: ['Bankesh','Bikaji','Zebra'] }
]

const entries = _.entries(_.countBy(_.flatMap(data, 'things')))
const thingsNames = _.orderBy(entries, [1, 0], ['desc', 'asc']);

console.log(thingsNames)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>

不要映射结果,而是使用 ngFor 创建文本和链接:

<div *ngFor = "let thingsName of thingsNames">

{{thingsName[0]}} (<a href="/url" >({{thingsName[1]}})</a>)

</div>

关于javascript - 我怎样才能以更有效的方式减少它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58988544/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com