[英]How to merge two arrays in Javascript
第一陣列
[{'value':'one','other':'othervalue'},{value:'two'},{value:'three'},{value:'four'}]
第二陣列
['one','two','six','five']
在這里,我想將第二個數組的值添加到第一個數組的value屬性,如果存在唯一的情況。 我試過循環所有的值,例如
for( var i=0; i < eLength; i++ ) {
for( var j = 0; j < rLength; j++ ) {
if( temp[j].values != enteredValues[i] ) {
console.log()
var priority = enteredValues.indexOf( enteredValues[i] ) + 1;
var obj = { 'values': enteredValues[i] };
}
}
reportbody.push( obj) ;
}
通過將對象設置為循環數據,可以將對象用作對象數組中值的哈希表。
然后檢查數組中是否有值,如果沒有,則將新對象推送到數據數組中。
var data = [{ value: 'one', other: 'othervalue' }, { value: 'two' }, { value: 'three' }, { value: 'four' }], values = ['one', 'two', 'six', 'five', 'six'], hash = Object.create(null); data.forEach(function (a) { hash[a.value] = true; }); values.forEach(function (a) { if (!hash[a]) { hash[a] = true; data.push({ value: a }); } }); console.log(data);
.as-console-wrapper { max-height: 100% !important; top: 0; }
var original = [{'value':'one','other':'othervalue'},{value:'two'},{value:'three'},{value:'four'}]; var toAdd = ['one','two','six','five']; // First make a dictionary out of your original array // This will save time on lookups var dictionary = original.reduce(function(p,c) { p[c.value] = c; return p; }, {}); // Now for each item in your new list toAdd.forEach(function(i) { // check that it's not already in the dictionary if (!dictionary[i]) { // add it to the dictionary dictionary[i] = { value: i }; // and to your original array original.push(dictionary[i]); } }); console.log(original);
在這里制作字典,我假設original
開始沒有任何重復。
盡管使用哈希表或字典可能會帶來性能優勢,但是最直接的實現是
second.forEach(s => {
if (!first.find(f => f.value === s)) first.push({value: s});
});
如果確實要使用哈希表,那么從語義上講,可能更喜歡使用Set:
const dict = new Set(first.map(f => f.value));
second.forEach(s => { if (!dict.has(s)) first.push({value: s}); });
上面的代碼將不會處理第二個數組中的重復項,因此,如果這是一個問題,則需要相應地進行調整。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.