Javascript如何检查json数组对象是否出现多次

时间:2016-12-22 13:04:38

标签: javascript arrays

"Rows":[
    [0:"2017-01-01", 1:"Ontdekkingstocht"],
    [0:"2017-01-01", 1:"Ontdekkingstocht"],
    [0:"2017-01-02", 1:"Ontdekkingstocht"]]

如何查看0:"2017-01-01"是否出现多次,如果是,则返回true?

3 个答案:

答案 0 :(得分:0)

这里有一个函数,你的数组作为参数:

function checkDuplicate(arr){
    var i = 0;
    while(i < arr.length-1){
        arr.slice(i+1).forEach(function(element) {
            if(element[0] == arr[i][0])return true;
        });
    }
    return false;
}

答案 1 :(得分:0)

这是一个快速的方法:

var data = {
  "Rows": [
    ["2017-01-01", "Ontdekkingstocht"],
    ["2017-01-01", "Ontdekkingstocht"],
    ["2017-01-02", "Ontdekkingstocht"]
  ]
};

function dupes(data) {
  var cnt = {};
  data.Rows.forEach((i) => { cnt[i[0]] = 1 });
  return Object.keys(cnt).length < data.Rows.length;
}

console.log(dupes(data));

答案 2 :(得分:0)

快速可读的方式是:

&#13;
&#13;
const rows = [
    ["2017-01-01", "Ontdekkingstocht"],
    ["2017-01-01", "Ontdekkingstocht"],
    ["2017-01-02", "Ontdekkingstocht"]
  ];

const duplicates = rows
  .reduce((prev, curr) => [...prev, ...curr])
  .some((element, index, array) => array.filter(el => element === el));

console.log(duplicates);
&#13;
&#13;
&#13;