gpt4 book ai didi

用于在最近结果上连续过滤数据的 JavaScript 算法

转载 作者:行者123 更新时间:2023-12-05 00:29:20 25 4
gpt4 key购买 nike

我需要编写一个算法,在该算法中,用户选择一个选项来过滤特定数据,并且在每次点击时都会发出一个返回过滤数据的 api 请求。用户点击的次数越多,它就需要继续过滤掉数据。我的问题是,算法如何保存最新结果并在最新结果上运行 for/filter 循环?我应该将最新结果存储在 localStorage 中以便进一步过滤结果吗?当用户决定取消选择他们想要过滤的数据时,它应该向用户显示他们之前的结果。用户应该能够继续过滤,直到他们获得所需的数据。请看下面的例子。

***DATA***
let data = [
{"id":0, "name":"John1", "age":29, "city":"seattle", "score": 95},
{"id":1, "name":"John2", "age":28, "city":"seattle", "score": 95},
{"id":2, "name":"John3", "age":29, "city":"seattle", "score": 85},
{"id":3, "name":"John4", "age":30, "city":"austin", "score": 75},
{"id":4, "name":"John5", "age":24, "city":"austin", "score": 85},
{"id":5, "name":"John6", "age":30, "city":"aspen", "score": 84},
{"id":6, "name":"John7", "age":31, "city":"aspen", "score": 100},
{"id":7, "name":"John8", "age":31, "city":"aspen", "score": 93},
{"id":8, "name":"John9", "age":35, "city":"denver", "score": 93},
{"id":9, "name":"John10", "age":29, "city":"denver", "score": 75},
{"id":10, "name":"John11", "age":28, "city":"denver", "score": 85},
{"id":11, "name":"John12", "age":28, "city":"denver", "score": 85},
]
***FIRST USER SELECTED FILTER***
let firstFilter = [{"score":85}]

***FIRST FILTER RESULTS***
let firstFilterdResults = [
{"id":2, "name":"John3", "age":29, "city":"seattle", "score": 85},
{"id":4, "name":"John5", "age":24, "city":"austin", "score": 85},
{"id":10, "name":"John11", "age":28, "city":"denver", "score": 85},
{"id":11, "name":"John12", "age":28, "city":"denver", "score": 85},
]
***SECOND USER SELECTED FILTER***
let secondFilter = [{"age":28}]

***SECOND FILTER RESULTS***
let secondFilterdResults = [
{"id":10, "name":"John11", "age":28, "city":"denver", "score": 85},
{"id":11, "name":"John12", "age":28, "city":"denver", "score": 85},
]
***CURRENT ALGORITHM***

function filterDataList(data, firstFilter) {
let firstFilteredResults = [];

firstFilteredResults = data.filter((dataItem) => {
var throwVar = 0
for (let item of firstFilter) {
for (let key in item) {
if (dataItem[key] === undefined || dataItem[key] !== item[key]) {
throwVar = 0
} else {
return true
}
}



}
if (throwVar == 0) {
return false
}
})

return firstFilteredResults

}

最佳答案

连续的过滤器选择实际上是指定键和值的结合......

age == x AND score == y AND ....
就像一个物体!
由于用户可能会多次做出这些选择,因此他们可能会产生错误的过滤器,例如: age == x AND age == y .
我们真的希望查询是唯一键与值的结合。
就像一个物体!
// this expresses a conjunction of unique keys - values
let query = {}

let data = [...]
let filteredData = []

// add a key-value, pair and update the filtered data
function addFilter(key, value) {
query[key] = value;

const keys = Object.keys(query);
filteredData = data.filter(datum => {
return keys.every(key => datum[key] === query[key])
});
}

function reset() {
query = {}
}

关于用于在最近结果上连续过滤数据的 JavaScript 算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70509423/

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