[英]Get specific data from array and put in other array
I have this result in javascript and i want to get data that has value more that 3 and i want to put in other array .我在 javascript 中有这个结果,我想获得值大于 3 的数据,我想放入其他数组。
"availableDates": {
"2020-01-24": 1,
"2020-01-23": 3,
"2020-01-22": 2,
"2020-01-21": 1,
"2020-01-25": 4,
"2021-01-07": 1
}
I group here :我在这里分组:
const formattedDate = x.reduce((acc,el) => {
const date = el.split(" ")[0];
acc[date] = (acc[date] || 0) + 1;
return acc;
}, {});
now I want to put in other array all that date that has value more than 3 .现在我想把值大于 3 的所有日期放入其他数组中。 For example例如
newarray = [ "2020-01-23", "2020-01-25" ]
Why don't use a simple .filter()
over keys of "availableDates"
:为什么不在"availableDates"
键上使用简单的.filter()
:
const grouped = { "availableDates": { "2020-01-24": 1, "2020-01-23": 3, "2020-01-22": 2, "2020-01-21": 1, "2020-01-25": 4, "2021-01-07": 1 } }; const newArray = Object.keys(grouped.availableDates).filter((key) => grouped.availableDates[key] >= 3); console.log(newArray);
You can simply use a for...in
loop to iterate over object keys and filter them:您可以简单地使用for...in
循环来迭代对象键并过滤它们:
const data = { "2020-01-24": 1, "2020-01-23": 3, "2020-01-22": 2, "2020-01-21": 1, "2020-01-25": 4, "2021-01-07": 1 }; const reducer = (obj, val) => { const result = []; for(key in obj) { if(obj[key] >= val) result.push(key); }; return result; }; console.log(reducer(data, 3));
You could have something like this.你可以有这样的事情。 I write a complete bunch of the code to make you able to copy/past to test我写了一堆完整的代码,使您能够复制/过去进行测试
var availableDates = new Array()
var availableDates = {
"2020-01-24": 1,
"2020-01-23": 3,
"2020-01-22": 2,
"2020-01-21": 1,
"2020-01-25": 4,
"2021-01-07": 1
}
var results = new Array();
for (date in availableDates){
if (availableDates[date] >= 3){
results.push(date)
}
}
console.log(results)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.