【问题标题】:Filtering in JavaScript or jQuery [closed]在 JavaScript 或 jQuery 中过滤 [关闭]
【发布时间】:2016-05-29 11:14:25
【问题描述】:

我正在尝试从 JSON 文件 (link to file) 中获取数据。 如果我必须按名称或发布年份排序,如何过滤 该二维数组中的内容。

谁能帮我解决这个问题。

【问题讨论】:

    标签: javascript jquery arrays json sorting


    【解决方案1】:

    使用jQuery.get() 获取您的api 响应,然后使用Array.prototype.sort() 进行排序。

    Year排序:

    $.get("http://www.omdbapi.com/?s=Batman&page=2", (result) => {
        result.Search.sort((a, b, by) => {
            return a.Year < b.Year ? -1 : a.Year > b.Year ? 1 : 0;
        });
        console.log(result);
    });
    &lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt;

    【讨论】:

    • 感谢您的澄清!这真的很有帮助
    【解决方案2】:

    您可以扩展原始Yosvel Quintero answer 以接受排序类型:

    function sort(type) {
        $.get("http://www.omdbapi.com/?s=Batman&page=2", ({ Search }) => {   
            Search.sort((a, b) => a[type] > b[type]);
            console.log(`Sorted by: ${type}`);
            console.log(Search);
        });
    }
    sort('Year');
    sort('Title');
    &lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt;

    【讨论】:

    • 谢谢!!很清楚
    【解决方案3】:

    function sort(type) {
        $.get("http://www.omdbapi.com/?s=Batman&page=2", ({ Search }) => {   
            Search.sort((a, b) => a[type] > b[type]);
            console.log(`Sorted by: ${type}`);
            console.log(Search);
        });
    }
    sort('Year');
    sort('Title');
    &lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt;

    function sort(type) {
        $.get("http://www.omdbapi.com/?s=Batman&page=2", ({ Search }) => {   
            Search.sort((a, b) => a[type] > b[type]);
            console.log(`Sorted by: ${type}`);
            console.log(Search);
        });
    }
    sort('Year');
    sort('Title');
    &lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt;

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-08-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-10
      • 2016-09-02
      • 2016-11-09
      • 2013-06-28
      相关资源
      最近更新 更多