JSFiddle对象排序算法崩溃

时间:2017-04-18 16:31:23

标签: javascript

我道歉,如果这是一个愚蠢的问题,我正在学习JS考试,并且我随机分配了一个任务,我在JSFiddle中按年份从URL中排序JSON数据。 代码如下:

https://jsfiddle.net/gs6eey97/ (i apologize for all the comments).

第一个问题是控制台返回排序列表,但每个已排序的元素在排序列表中出现两次(Console result)。我想在排序数据放入数组之前添加一个if语句来过滤重复项改变了以下几点:

minYear.push(minYearPom);
minSort.push(propPom); 

以下内容:

if (propPom != minSort[minSort.length - 1]) {
        minYear.push(minYearPom);
        minSort.push(propPom);
      }

并且Chrome停止响应,我已尝试删除

minYear.push(minYearPom);

因为我意识到我并不真的需要它,Chrome停止响应,我添加简单的console.log来查看某些变量的值,以试图找出问题所在,并且Chrome停止响应。朋友可以&似乎找不到代码的问题,所以如果有人能找到问题,我真的很感激。

2 个答案:

答案 0 :(得分:2)

当你得到一个带物体的物体时,

{
    movies: {
        tt0111161: {
            Title: "The Shawshank Redemption",
            Year: "1994",
            Runtime: "142",
            Director: "Frank Darabont",
            Actors: [
              "Tim Robbins",
              "Morgan Freeman",
              "Bob Gunton",
              "William Sadler"
            ],
            Language: [
              "English"
            ],
            imdbRating: "9.3",
            imdbVotes: "138"
        },
        // ...
    }
}

您需要使用密钥,例如tt0111161等,并对密钥数组应用排序:

var data = { movies: { tt0111161: { Title: "The Shawshank Redemption", Year: "1994", Runtime: "142", Director: "Frank Darabont", Actors: ["Tim Robbins", "Morgan Freeman", "Bob Gunton", "William Sadler"], Language: ["English"], imdbRating: "9.3", imdbVotes: "138" }, tt0068646: { Title: "The Godfather", Year: "1972", Runtime: "175", Director: "Francis Ford Coppola", Actors: ["Marlon Brando", "Al Pacino", "James Caan", "Richard S. Castellano"], Language: ["English", "Italian", "Latin"], imdbRating: "9.2", imdbVotes: "96" } } },
    keys = Object.keys(data.movies);

keys.sort(function (a, b) {
    return data.movies[a].Year - data.movies[b].Year;
});

console.log(keys);
.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 1 :(得分:1)

我们使用Object.prototype.values()将电影作为对象数组获取:

  

Object.values()方法返回给定对象自己的数组   可枚举的属性值,与a提供的顺序相同   for...in loop(不同之处在于for-in循环枚举   原型链中的属性也是如此。

let movies = Object.values(data.movies);

/*
movies = [
    { "Title": "The Shawshank Redemption", ... },
    { "Title": "The Godfather", ... },
    ...
];
*/

currentYear用于计算电影的年龄

然后我们使用Array.prototype.sort()对电影进行排序:

  

sort()方法对数组中的元素进行排序并返回   数组。排序不一定稳定。默认排序顺序   是根据字符串Unicode代码点。

movies.sort((a, b) => a.Year - b.Year);

对于电影的平均年龄,我们使用Array.prototype.reduce()

  

reduce()方法对累加器和每个应用函数   数组中的元素(从左到右)将其缩小为单个元素   值。

let avg = movies.reduce((result, currentMovie) => result + (currentYear - currentMovie.Year), 0) / movies.length;

也在代码段中使用但与排序/平均部分无关:

Arrow function (... => ...)

  

箭头函数表达式的语法短于函数   表达式并不绑定它自己的this,arguments,super或   new.target。这些函数表达式最适合非方法   函数,它们不能用作构造函数。

Template literals (`...${...}...`)

  

模板文字是允许嵌入表达式的字符串文字。   您可以使用多行字符串和字符串插值功能   他们。他们被称为"模板字符串"在以前的版本中   ES2015规范。



let data = { "movies":{ "tt0111161":{ "Title":"The Shawshank Redemption", "Year":"1994", "Runtime":"142", "Director":"Frank Darabont", "Actors":["Tim Robbins", "Morgan Freeman", "Bob Gunton", "William Sadler"], "Language":["English"], "imdbRating":"9.3", "imdbVotes":"138" }, "tt0068646":{ "Title":"The Godfather", "Year":"1972", "Runtime":"175", "Director":"Francis Ford Coppola", "Actors":["Marlon Brando", "Al Pacino", "James Caan", "Richard S. Castellano"], "Language":["English", "Italian", "Latin"], "imdbRating":"9.2", "imdbVotes":"96" }, "tt0071562":{ "Title":"The Godfather: Part II", "Year":"1974", "Runtime":"200", "Director":"Francis Ford Coppola", "Actors":["Al Pacino", "Robert Duvall", "Diane Keaton", "Robert De Niro"], "Language":["English", "Italian", "Spanish", "Latin", "Sicilian"], "imdbRating":"9.1", "imdbVotes":"64" }, "tt0468569":{ "Title":"The Dark Knight", "Year":"2008", "Runtime":"152", "Director":"Christopher Nolan", "Actors":["Christian Bale", "Heath Ledger", "Aaron Eckhart", "Michael Caine"], "Language":["English", "Mandarin"], "imdbRating":"9.0", "imdbVotes":"137" }, "tt0110912":{ "Title":"Pulp Fiction", "Year":"1994", "Runtime":"154", "Director":"Quentin Tarantino", "Actors":["Tim Roth", "Amanda Plummer", "Laura Lovelace", "John Travolta"], "Language":["English", "Spanish", "French"], "imdbRating":"8.9", "imdbVotes":"108" } } }
    movies = Object.values(data.movies),
    currentYear = new Date().getFullYear();

movies.sort((a, b) => a.Year - b.Year);
let avg = movies.reduce((result, currentMovie) => {
              return result + (currentYear - currentMovie.Year);
          }, 0) / movies.length;

movies.forEach(movie => console.log(`Title: ${movie.Title} (${movie.Year})`));
console.log(`Average age: ${avg}`);