删除object属性不唯一的数组项

时间:2017-04-06 11:50:00

标签: javascript arrays reactjs

我有一个包含对象的数组,我需要根据data-itemid道具删除重复项。

这是我的代码:

const ListItemsUnique = []
ListItems.map(item => {
  if (ListItemsUnique.indexOf(item.props['data-itemid']) === -1) {
    ListItemsUnique.push(item)
  }
});

它返回与以前完全相同的数组,我做错了什么?

3 个答案:

答案 0 :(得分:2)

如果您使用的是ES6,请尝试使用

Try
    If MsgBox("Is your information correct?", MsgBoxStyle.YesNo, "M&P Records") = MsgBoxResult.Yes Then
        Dim pattern As String = "^[A-Z][A-Z|0-9|]*[a-z][a-z|0-9|]*([_][a-z|0-9]+)*([.][a-z|0-9]+([_][a-z|0-9]+)*)?@[a-z][a-z|0-9|]*\.([a-z][a-z|0-9]*(\.[a-z][a-z|0-9]*)?)$"
        Dim match As System.Text.RegularExpressions.Match = Regex.Match(txtUsername.Text.Trim(), pattern, RegexOptions.IgnoreCase)
        If (match.Success) Then
            Dim passwordFound As Boolean
            Dim userFound As Boolean
            Using con As New SqlClient.SqlConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source =\ 11_2017_Spring\CSCI-2999_Capstone\DB_M&PRecords.accdb")
                'Using to make sure connection is disposed
                'Open connection
                con.Open()
                'Prepare sql
                Dim command As New OleDbCommand("SELECT [emailAddress] FROM [EmailAddress] WHERE [emailAddress] = '" & txtUsername.Text & "';", con)
                'Create the reader
                Dim reader As OleDbDataReader = command.ExecuteReader()
                Dim Id As String = ""
                ' Call Read before accessing data.
                While reader.Read()
                    'Get data
                    Id = reader(0)
                End While
                'Close Reader
                reader.Close()
                If Id <> "" Then
                    'User found
                    userFound = True
                    'Prepare the second sql 
                    Dim command2 As New OleDbCommand("SELECT [Password] FROM [Password] WHERE [Password] = '" & txtPassword.Text & "';", con)
                    'Prepare second reader
                    Dim reader2 As OleDbDataReader = command.ExecuteReader()
                    Dim Pass As String = ""
                    ' Call Read before accessing data.
                    While reader2.Read()
                        'Get tdata
                        Pass = reader2(0)
                    End While
                    reader.Close()
                    If Pass <> "" Then
                        'Pass found
                        passwordFound = True
                    Else
                        passwordFound = False
                    End If
                Else
                    userFound = False
                End If
                'Close connection
                con.Close()
                'Clear connection pool
                SqlConnection.ClearPool(con)
            End Using
            'checking the result
            If userFound = True And passwordFound = True Then
                frmMain.Show()
                frmMain.Label1.Text = "Welcome " & EmailAddressText & " "
            Else
                MsgBox("Sorry, username or password not found", MsgBoxStyle.OkOnly, "M&P Records - Invalid Login")
                With txtPassword
                    .Clear()
                End With
                With txtUsername
                    .Clear()
                    .Focus()
                End With
            End If
        Else
            MessageBox.Show("Please enter a valid email address", "M&P Records - Email Check")
            With txtPassword
                .Clear()
            End With
            With txtUsername
                .Clear()
                .Focus()
            End With
        End If
    End If
Catch ex As Exception
    '  An error occured!  Show the error to the user and then exit.
    MessageBox.Show(ex.Message)
End Try

编辑1:

const ListItemsUnique = [...new Set(ListItems.map(item => item.props['data-itemid']))];

DEMO:https://codepen.io/vedp/pen/RpmVvx?editors=0011

答案 1 :(得分:1)

最简单,最干净的方法是使用临时集来存储您之前返回到阵列的项目,同时通过它进行映射。像这样:

let tempSet = new Set();
const ListItemsUnique = ListItems.filter(item => {
  if(!tempSet.has(item.props['data-itemid'])) {
      tempSet.add(item.props['data-itemid']);
    return item;
  }
});

然后像往常一样进行映射。

演示

&#13;
&#13;
let ListItems = [
  {name: "A", props: {"data-itemid": 1}},
  {name: "B", props: {"data-itemid": 1}},
  {name: "C", props: {"data-itemid": 2}},
  {name: "D", props: {"data-itemid": 3}},
  {name: "E", props: {"data-itemid": 3}},
];  //mock data

let tempSet = new Set();
const ListItemsUnique = ListItems.filter(item => {
  if(!tempSet.has(item.props['data-itemid'])) {
    tempSet.add(item.props['data-itemid']);
    return item;
  }
})

console.log(ListItemsUnique.map(item => item.name));  //Items "B" and "E" are skipped
&#13;
&#13;
&#13;

顺便说一下,Set非常适合处理或想要实现独特的数据集合。有关Set的更多信息,请阅读MDN

以下是文档的摘录:

  

Set个对象是值的集合。您可以按插入顺序遍历集合的元素。 Set中的值可能只出现一次;它在Set集合中是唯一的。

答案 2 :(得分:1)

你也可以使用不可变的js或JSON.stringify(取决于你的对象深度或你想要比较的深度;)

  1. 使用immutablejs - fromJS + compare
  2. 使用JSON.stringify
  3. JSON.stringify的示例

    const ListItems = [{a: 'a'}, {a: 'b'}, {a: 'a'}];
    
    let ListItemsUnique = [];
    let stringList = [];
    
    ListItems.forEach(item => {
        const itemString = JSON.stringify(item);
        if (stringList.indexOf(itemString) === -1) {
            ListItemsUnique.push(item);
        }
        stringList.push(itemString);
    })
    
    console.log(ListItemsUnique);