gpt4 book ai didi

javascript计算数组中的重复字符串并将其分组

转载 作者:行者123 更新时间:2023-11-30 09:33:47 24 4
gpt4 key购买 nike


我有这个数组:

["2017-06-21", "2017-06-21", "2017-06-21", "2017-06-21", "2017-06-21", "2017-06-21", "2017-06-21", "2017-06-21", "2017-06-21", "2017-06-21", "2017-06-21", "2017-06-21", "2017-06-21", "2017-06-21", "2017-06-21", "2017-06-21", "2017-06-21", "2017-06-21", "2017-06-21", "2017-06-21", "2017-06-21", "2017-06-21", "2017-06-21", "2017-06-21", "2017-06-21", "2017-06-22", "2017-06-22", "2017-06-22", "2017-06-23", "2017-06-23", "2017-06-23", "2017-06-23", "2017-06-23", "2017-06-23", "2017-06-23", "2017-06-23", "2017-06-23", "2017-06-23", "2017-06-23", "2017-06-23", "2017-06-23", "2017-06-23", "2017-06-23", "2017-06-25", "2017-06-26", "2017-06-26", "2017-06-26", "2017-06-26", "2017-06-26", "2017-06-26", "2017-06-26", "2017-06-26", "2017-06-26", "2017-06-26", "2017-06-27"]

我正在尝试编写代码以在输出中获取此内容:

['date', "2017-06-2", "2017-06-22", "2017-06-23", "2017-06-24", "2017-06-25"]
['repeated_count', 5, 9, 3, 8, 4]


这是我所做的,但这是错误的:


var ChartDate = the above data ↑
var ChartDates = [];
var RepeatedNum = [];
for (i =0; i <= ChartDate.length; i++) {
if (ChartDates.indexOf(ChartDate[i]) < 0) {
if (typeof ChartDate[i] !== 'undefined') {
ChartDates.push(ChartDate[i]);
RepeatedNum.push('T');
}
}else {
RepeatedNum.push(1);
}
}
console.log(ChartDates);
console.log(RepeatedNum);


我该如何解决这个问题。感谢您的帮助

最佳答案

首先,循环遍历数组中的所有日期并将它们统计到 tally 对象中,方法是将与日期对应的键(如果已经存在)递增 1,或者创建一个具有值的新键如果没有,则为 1。之后,对对象执行 for-in 循环,并用日期填充 uniqueDates 数组,用重复次数填充 repeatedNumber 数组。

const dates = ["2017-06-21", "2017-06-21", "2017-06-21", "2017-06-21", "2017-06-21", "2017-06-21", "2017-06-21", "2017-06-21", "2017-06-21", "2017-06-21", "2017-06-21", "2017-06-21", "2017-06-21", "2017-06-21", "2017-06-21", "2017-06-21", "2017-06-21", "2017-06-21", "2017-06-21", "2017-06-21", "2017-06-21", "2017-06-21", "2017-06-21", "2017-06-21", "2017-06-21", "2017-06-22", "2017-06-22", "2017-06-22", "2017-06-23", "2017-06-23", "2017-06-23", "2017-06-23", "2017-06-23", "2017-06-23", "2017-06-23", "2017-06-23", "2017-06-23", "2017-06-23", "2017-06-23", "2017-06-23", "2017-06-23", "2017-06-23", "2017-06-23", "2017-06-25", "2017-06-26", "2017-06-26", "2017-06-26", "2017-06-26", "2017-06-26", "2017-06-26", "2017-06-26", "2017-06-26", "2017-06-26", "2017-06-26", "2017-06-27"];

const tally = {};
const uniqueDates = ['date'];
const repeatedNumber =['repeated_count'];

for(let i = 0; i < dates.length; i++) {
if(tally.hasOwnProperty(dates[i])) {
tally[dates[i]]++;
} else {
tally[dates[i]] = 1;
}
};

for(let date in tally) {
uniqueDates.push(date);
repeatedNumber.push(tally[date]);
}

console.log(uniqueDates);
console.log(repeatedNumber);

关于javascript计算数组中的重复字符串并将其分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44771126/

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