gpt4 book ai didi

javascript - 返回发行专辑最多的年份的函数

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:27:28 24 4
gpt4 key购买 nike

以下是甲壳虫乐队发行年份的专辑列表。编写一个返回年份的函数大多数专辑发行。如果有一年,返回一个字符串,否则返回一个数组。

var beatles_discography = {
"Please Please Me": 1963,
"With the Beatles": 1963,
"A Hard Day's Night ": 1964,
"Beatles for Sale ": 1964,
"Twist and Shout ": 1964,
"Help ": 1965,
"Rubber Soul ": 1965,
"Revolver": 1966,
"Sgt. Pepper's Lonely Hearts Club Band": 1967,
"Magical Mystery Tour ": 1967,
"The Beatles ": 1968,
"Yellow Submarine ": 1969 ,
"Abbey Road": 1969,
"Let It Be ": 1970
}

到目前为止,我试着喜欢这个:-

var x = {
"Please Please Me": 1963,
"With the Beatles": 1963,
"A Hard Day's Night ": 1964,
"Beatles for Sale ": 1964,
"Twist and Shout ": 1964,
"Help ": 1965,
"Rubber Soul ": 1965,
"Revolver": 1966,
"Sgt. Pepper's Lonely Hearts Club Band": 1967,
"Magical Mystery Tour ": 1967,
"The Beatles ": 1968,
"Yellow Submarine ": 1969 ,
"Abbey Road": 1969,
"Let It Be ": 1970
}
var y = {};

for (var key in x){
y[x[key]] = y[x[key]] ? y[x[key]] + 1: 1;
}
var arr = Object.keys(y);
function getYear(arr){
for (var m=0; m<arr.length -1; m++){
if(y[arr[0]] > y[arr[1]]){
return arr[0];
}else{
var temp = [];
if(y[m] == y[m+1]){
temp.push(arr[m],arr[m+1]);
}
return temp;
}
}
}

console.log(getYear(arr));

此代码的预期输出是 1964,因为在列表中我今年只重复了 3 次。如果在对象中我也有 1965 3 次,那么我需要返回一个像 [1964, 1965] 这样的数组。感谢您的帮助。

最佳答案

var albums = {
"Please Please Me": 1963,
"With the Beatles": 1963,
"A Hard Day's Night ": 1964,
"Beatles for Sale ": 1964,
"Twist and Shout ": 1964,
"Help ": 1963,
"Rubber Soul ": 1965,
"Revolver": 1966,
"Sgt. Pepper's Lonely Hearts Club Band": 1967,
"Magical Mystery Tour ": 1967,
"The Beatles ": 1968,
"Yellow Submarine ": 1969,
"Abbey Road": 1969,
"Let It Be ": 1970
}


function getYear(albums) {
var albumOccurrence = {};
var max = 0;
var res = [];
for (var key in albums) {
albumOccurrence[albums[key]] = albumOccurrence[albums[key]] ? albumOccurrence[albums[key]] + 1 : 1;
if (albumOccurrence[albums[key]] > max)
max = albumOccurrence[albums[key]];
}
console.log(max, albumOccurence);
for (var occurrence in albumOccurrence) {
if (albumOccurrence[occurrence] == max) {
res.push(occurrence);
}
}
if (res.length == 1) {
res = res[0];
}
return res;
}
console.log(getYear(albums));

这是你要找的吗?

关于javascript - 返回发行专辑最多的年份的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53919538/

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