按日期过滤数组,之后按JavaScript中的名称

时间:2016-04-08 15:46:57

标签: javascript arrays sorting

我在js中有一个名为:areas

的数组
var areas =  [
 ["Id" : 1, "Date" : "2016-04-01", "Name" : "Ramon"],
 ["Id" : 2, "Date" : "2016-04-01", "Name" : "Ester"],
 ["Id" : 3, "Date" : "2016-04-01", "Name" : "Sandy"],
 ["Id" : 4, "Date" : "2016-04-02", "Name" : "Ruiz"],
 ["Id" : 5, "Date" : "2016-04-03", "Name" : "Mark"],
 ["Id" : 6, "Date" : "2016-04-04", "Name" : "Vadim"],
 ["Id" : 7, "Date" : "2016-04-06", "Name" : "Vanny"],
 ["Id" : 8, "Date" : "2016-04-09", "Name" : "John"]
]

例如在之前我在ajax中有一个过滤器,它将按日期和时间对它们进行分类 我正在做的事情:

for (var i = 0; i < areas.length; i++ ){
      console.log("Date " + areas[i].Date + " Name " + areas[i].Name);
}

输出将是

Date 2016-04-01 Name Ramon
Date 2016-04-01 Name Ester
Date 2016-04-01 Name Sandy
Date 2016-04-02 Name Ruiz

但我想要按名称过滤的日期相同

这样:

Date 2016-04-01 Name Ester
Date 2016-04-01 Name Ramon
Date 2016-04-02 Name Ruiz
Date 2016-04-01 Name Sandy

我需要制作另一个循环或如何?

由于

1 个答案:

答案 0 :(得分:0)

https://jsfiddle.net/whr4taug/

Filter an array by date and after that by Name in JavaScript

你的问题不言而喻 - 你需要过滤函数,js有 - https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

它可以在一个循环中完成所有排序。或者你可以添加多个功能,每个功能都有它的排序

var areas =  [
    {"Id" : 1, "Date" : "2016-04-01", "Name" : "Ramon"},
    {"Id" : 2, "Date" : "2016-04-01", "Name" : "Ester"},
    {"Id" : 3, "Date" : "2016-04-01", "Name" : "Sandy"},
    {"Id" : 4, "Date" : "2016-04-02", "Name" : "Ruiz"},
    {"Id" : 5, "Date" : "2016-04-03", "Name" : "Mark"},
    {"Id" : 6, "Date" : "2016-04-04", "Name" : "Vadim"},
    {"Id" : 7, "Date" : "2016-04-06", "Name" : "Vanny"},
    {"Id" : 8, "Date" : "2016-04-09", "Name" : "John"}
]

var filtered = areas.filter(function(el){
    if (el.Name == 'Ramon' && el.Date == '2016-04-01') return el;
});

console.log(filtered);

你的areas decalration也是错的(不确定是否拼写错误) - js没有相关的数组,只有那个目的的对象

如果您的要求是使用ajax,那么我不确定为什么你需要js?只做两个ajax请求,这就是

如果你想在for循环中过滤它们,只需使用相同的比较

for (var i = 0; i < areas.length; i++ ){
  if (areas[i].Name == 'Ramon' && areas[i].Date == '2016-04-01') {
    console.log("Date " + areas[i].Date + " Name " + areas[i].Name);
  }
}