在Javascript中的Array中插入唯一值

时间:2017-12-04 06:08:00

标签: javascript arrays angularjs

我有一个阵列。该函数从后端服务连续调用。 我想在一个对象中推送唯一值。我的代码是

currentValue =  pointerToVisconCtrl.MappedVariableObj.value;
var seconds = new Date().getSeconds();
seconds = parseInt(seconds);
graphDataObject.push({timestamp : seconds, value : currentValue});

请指导我在graphDataObject

中仅输入唯一的currentValue和seconds值

3 个答案:

答案 0 :(得分:1)

var finalArr = graphDataObject.filter(function(d){
if(d.value == currentValue){ return d;}
});

if(finalArr.length == 0){
graphDataObject.push({timestamp : seconds, value : currentValue});
}

答案 1 :(得分:0)

您可以在javascript数组中使用过滤函数,如下所示,检查特定对象是否存在:

    function getData(){
var city=document.getElementById("startCity").value;
var State=document.getElementById("startState").value;
var endCity=document.getElementById("endCity").value;
var endState=document.getElementById("endState").value;
console.log(city);    
var s=   document.getElementById("demo").innerHTML = endState;
}
First you get value from form like this or you can serialize the form , then you emebed your logic 

答案 2 :(得分:0)

使用过滤功能和||避免重复

let graphDataObject = [{timestamp : 11, value : 11},{timestamp : 4, value : 44},{timestamp : 2, value : 22},{timestamp : 3, value : 24}]


let newObject = {timestamp : 11, value : 24}


let result = graphDataObject.filter((obj) => {
    return obj.timestamp == newObject["timestamp"] || obj.value == newObject["value"];
})

if(result.length > 1) {
  // already present.. do your logic
}