过滤数组(javascript)

时间:2017-03-27 17:18:22

标签: javascript arrays

我有一个数组数组,并且在每个数组中它们都是日期和随机值。

我有一个日期选择器,一旦我点击了一个日期,我就持有该日期的价值。

示例

var array = [ ["02-01-2017 09:20:21", 116],
    ["02-13-2017 19:07:57", 133],
    ["01-28-2017 10:27:15", 29],
    ["02-14-2017 06:56:22", 137],
    ["02-22-2017 09:23:43", 208],
    ["01-15-2017 23:33:40", 120],
    ["01-16-2017 05:21:05", 146],
    ["01-02-2017 01:49:32", 209],
    ["02-14-2017 06:19:54", 172],
    ["01-02-2017 02:12:16", 13],
    ["02-25-2017 11:39:00", 213],
    ["01-01-2017 15:27:43", 39],
    ["01-10-2017 17:58:27", 96],
    ["02-10-2017 18:17:42", 99],
    ["01-04-2017 21:28:33", 40],
    ["02-08-2017 18:09:55", 92],
    ["02-08-2017 10:24:47", 12],
    ["02-03-2017 19:49:59", 15],
    ["01-07-2017 16:52:17", 196]
]

所以一旦我点击了我的日期选择器中的日期,比如02-08-2017,我想过滤掉我的大数组,所以最后我的数组只有包含所选日期的数组。

var newArray = [
        ["02-08-2017 18:09:55", 92],
        ["02-08-2017 10:24:47", 12]
]

那我该怎么做?不使用任何jquery

2 个答案:

答案 0 :(得分:0)

您需要Array.prototype.filter,它接受一个函数并将其应用于数组的每个元素。如果函数返回true,则传递的元素将作为结果返回。

例如:

let result = sourceArray.filter((elt) => elt[0].match(/^02-08-2017$/))

答案 1 :(得分:0)

您可以使用过滤器并转换Date()对象中的字符串,并使用toDateString()来比较它们忽略小时数并仅考虑日期



var array = [ ["02-01-2017 09:20:21", 116], ["02-13-2017 19:07:57", 133], ["01-28-2017 10:27:15", 29], ["02-14-2017 06:56:22", 137], ["02-22-2017 09:23:43", 208], ["01-15-2017 23:33:40", 120], ["01-16-2017 05:21:05", 146], ["01-02-2017 01:49:32", 209], ["02-14-2017 06:19:54", 172], ["01-02-2017 02:12:16", 13],  ["02-25-2017 11:39:00", 213], ["01-01-2017 15:27:43", 39], ["01-10-2017 17:58:27", 96], ["02-10-2017 18:17:42", 99], ["01-04-2017 21:28:33", 40], ["02-08-2017 18:09:55", 92], ["02-08-2017 10:24:47", 12], ["02-03-2017 19:49:59", 15], ["01-07-2017 16:52:17", 196] ]

const selectedDate = "02-08-2017";
const transformedDate = new Date(selectedDate).toDateString()

const result = array.filter(el => new Date(el[0]).toDateString() === transformedDate)

console.log(result)