在javascript中获取带有列表的对象

时间:2018-07-25 21:53:50

标签: javascript arrays dictionary

我有一个数组p1,我正在尝试获取一个类似于[2, 2, 4, 3]的字典,该字典基本上是一个字典,其中在数组中包含{2:[0,1], 3:3, 4:2}items ,其keyindices,如果存在多个具有相同项目的索引,则将该值作为数组存储在字典中,否则作为普通值存储。

value

以上代码段仅将数组中该项的最新实例作为键并将其存储为值,如果数组中存在重复的多个项,则可以通过该方法将字典的值作为数组。另外,我是javascript的初学者,因此请忽略它是否是一个愚蠢的问题。

3 个答案:

答案 0 :(得分:1)

var arr = [2,2,4,3];
var dict={};
var len=arr.length;
for(var i=0; i<len; i++) {
   if(dict[arr[i]] !== undefined)
   {
     if(Array.isArray(dict[arr[i]]))
     {
       dict[arr[i]].push(i);
     }
     else
     {
       dict[arr[i]] = [dict[arr[i]]];
       dict[arr[i]].push(i);
     }
   }
   else
     dict[arr[i]] = i;
}

console.log(dict);

答案 1 :(得分:1)

一种替代方法是使用函数reduce对带有索引的值进行分组。

let arr = [2, 2, 4, 3],
    result = arr.reduce((a, c, i) => {
      let current = a[c];
      if (current || current === 0) {
        if (Array.isArray(current)) current.push(i);
        else a[c] = [current, i];
      } else a[c] = i;
      
      return a
    }, {});
    
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 2 :(得分:1)

可以很简单地完成

Sub zz()
    Dim sSQL As String, sResult(3) As String
    sSQL = "INSERT INTO [DataSheet2$] (Name, a, b, c, d, e) 
            VALUES ('This is a name', 10, 20, 30, 40, 50)"
    'Result is the array which is populated with the returned rows
    runQuery sSQL, sResult
End Sub



Public Function runQuery(SQL As String, ByRef result() As String) As Integer
  Dim dataConection As New ADODB.Connection
  Dim mrs As New ADODB.Recordset
  Dim DBPath As String
  Dim connectionString As String
  Dim size As Integer

  Set mrs = CreateObject("ADODB.Recordset")

  'Set cursor to start
  mrs.CursorLocation = adUseClient

  'Set database path
  DBPath = ThisWorkbook.FullName

  'You can provide the full path of your external file as shown below
  connectionString = "Provider=MSDASQL.1;DSN=Excel Files;DBQ=" & DBPath & ";HDR=Yes';"

  'Open connection to database
  dataConection.Open connectionString

  'Open record set (query or table, connection)
  mrs.Open SQL, dataConection   '>> this is where the INSERT happens

  'Record set returned update data
  If mrs.EOF Then   ''>> rte 3704  Operation not allowed when object is closed
      runQuery = 0
      Exit Function
  Else
      runQuery = mrs.RecordCount
  End If

  'Populate array with result
  ReDim result(size) As String
  Dim i As Integer

  For i = 0 To (size - 1)
      result(i) = mrs!Name
      mrs.MoveNext
  Next i

  'Close record set and connection
  mrs.Close
  dataConection.Close
End Function

或者,一成不变:

const dict = array.reduce((result, value, index) => {
  if (!result[value]) {
    result[value] = [index];
  } else {
    result[value].push(index);
  }
  return result;
}, {});