通过第一个对象从数组数组中删除重复项

时间:2015-05-28 11:54:28

标签: javascript arrays

我有一个数组数组,如下所示:

arr = [
["Bob","USA","55"],
["Frank","Canada","20"],
["Bob","UK","35"],
["Bob","France","38"],
["Anna","Poland","22"]
]

我想删除在第一个位置(相同名称)具有相同值的重复数组 - 所以我希望我的输出看起来像这样:

arr = [
["Bob","USA","55"],
["Frank","Canada","20"],
["Anna","Poland","22"]
]

我试图以这种方式做到这一点:

uniqueArr = []
for (var i in arr) {
if (uniqueArr.indexOf(arr[i][0]) === -1)) {
uniqueArr.push(arr[i][0])
}

一切正常 - 我的输出看起来像Bob,Frank,Anna

但问题是当我尝试使用唯一值名称重新获取整个数组时。当我在做的时候:

uniqueArr = []
for (var i in arr) {
if (uniqueArr.indexOf(arr[i][0]) === -1)) {
uniqueArr.push(arr[i])
}

我的输出看起来与输入数组完全一样。你知道我在哪里做错了吗?

3 个答案:

答案 0 :(得分:4)

您可以在单独的数组中跟踪key字符串,然后跟踪它,例如:

var uniqueArr = [],
    keys = []; // Create an array for storing the key values
for (var i in arr) {    
    if (keys.indexOf(arr[i][0]) === -1) {
        uniqueArr.push(arr[i]); // Push the value onto the unique array
        keys.push(arr[i][0]); // Push the key onto the 'key' array
    }
}
console.log(uniqueArr);

jsFiddle example

答案 1 :(得分:0)

 session_start();
    include("require_pro.php");

    $myusername = addslashes($_POST['username']);
    $password = addslashes($_POST['password']);
    $mypassword = md5($password);


    $query = mysql_query("SELECT * FROM user WHERE username='$myusername'and password ='$mypassword'") or die (mysql_error());
    $count = mysql_num_rows($query);

    if($count == 1) {
        echo "Login Successfully";
    } 

<强> DEMO

答案 2 :(得分:0)

看看功能unique2。它有效!

&#13;
&#13;
originalArr = [
  ["Bob", "USA", "55"],
  ["Frank", "Canada", "20"],
  ["Bob", "UK", "35"],
  ["Bob", "France", "38"],
  ["Anna", "Poland", "22"]
];

function unique(arr) {
  uniqueArr = [];
  for (var i in arr) {
    if (uniqueArr.indexOf(arr[i][0]) === -1) {
      uniqueArr.push(arr[i]);
    }
  }
  return uniqueArr;
}

function unique2(arr) {
  uniqueArr = [];
  keys = [];
  for (var i in arr) {
    if (keys.indexOf(arr[i][0]) === -1) {
      uniqueArr.push(arr[i]);
      keys.push(arr[i][0]);
    }
  }
  return uniqueArr;
}



var response = document.getElementById('response');
response.textContent = JSON.stringify(unique(originalArr));

var response2 = document.getElementById('response2');
response2.textContent = JSON.stringify(unique2(originalArr));
&#13;
<h1>Your code</h1>
<div id="response"></div>

<h1>My code</h1>
<div id="response2"></div>
&#13;
&#13;
&#13;