【问题标题】:Javascript Add new element to array of elements if not existsJavascript 如果不存在,则将新元素添加到元素数组
【发布时间】:2020-10-25 08:49:44
【问题描述】:

我有一个类似的数组:

 [{"x": 2020-06-27T08:00:00.000Z, "y": 33},
 {"x": 2020-06-27T10:00:00.000Z, "y": 500},
 {"x": 2020-06-27T12:00:00.000Z, "y": 98},
 {"x": 2020-06-27T14:00:00.000Z, "y": 344},
 {"x": 2020-06-27T22:00:00.000Z, "y": 1}]

数组已经从最早到最新进行了预排序。我需要做的是通过数组的“x”(这是一个日期),并检查是否有一些偶数小时(如 0、2、4 .. 或 22)不存在,如果不存在,则添加新的日期中包含该小时“x”且“y”值为零的条目。

有什么有效的方法吗? 最后,数组应该是这样的:

[{"x": 2020-06-27T00:00:00.000Z, "y": 0},
 {"x": 2020-06-27T02:00:00.000Z, "y": 0},
 {"x": 2020-06-27T04:00:00.000Z, "y": 0},
 {"x": 2020-06-27T06:00:00.000Z, "y": 0},
 {"x": 2020-06-27T08:00:00.000Z, "y": 33}, 
 {"x": 2020-06-27T10:00:00.000Z, "y": 500}]

等等,

【问题讨论】:

  • 我会建议将数组转换为以日期为键的对象,或者将日期和'y'值放在两个不同的数组中。
  • 如果你坚持使用数组而不是对象,你需要迭代检查x是否存在。为此,您可以使用二进制搜索,因为您的数组已排序。
  • 您是在检查单个值,还是检查所有缺少偶数小时的实例?

标签: javascript arrays reactjs reduce


【解决方案1】:

使用moment lib生成所有的时间表,然后使用map函数传递数组。

var start = moment.utc("2020-06-27").startOf('day'); 
var end = moment.utc("2020-06-27").endOf('day'); 

const origArray = [{"x": "2020-06-27T08:00:00.000Z", "y": 33},{"x": "2020-06-27T10:00:00.000Z", "y": 500},{"x": "2020-06-27T12:00:00.000Z", "y": 98},{"x": "2020-06-27T14:00:00.000Z", "y": 344},{"x": "2020-06-27T22:00:00.000Z", "y": 1}]

const schedulesArray = []
let currentTime = start
while (currentTime.isBefore(end)){
    schedulesArray.push(currentTime.toISOString())
  currentTime = currentTime.add(2, 'hours')
}
const newArray = schedulesArray.map(t => {
    const existingOrig = origArray.filter(o => o.x === t)
  if(existingOrig.length > 0){
    return JSON.stringify(existingOrig[0])
  }else{
    const newObj = {}
    newObj.x = t
    newObj.y = 0
    return JSON.stringify(newObj)
  }
});

console.log('arr ' + newArray)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.2.1/moment.min.js"></script>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-05-04
    • 1970-01-01
    • 1970-01-01
    • 2015-12-03
    • 2023-04-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多