![](/img/trans.png)
[英]Compare two Arrays with Objects and create new array with unmatched objects
[英]how to compare arrays and create new array that matches with array a?
我想匹配兩個數組,如果數組b
包含數組ai的字符串值要創建新數組,則使用下面的代碼將所有對象從數組b推入。 我如何只推入匹配的物體?
ctrl.js
var a = ["standard","industry","4578595"]
var b = [{file:"server.log",value:"lorem ipsum industry standard 4578595"}, {file:"server.log",value:"lorem ipsum industry standadr"},{file:"server.log",value:"lorem ipsum industry"}];
var finalyArray = [];
function compareArrays() {
for (i = 0; i < a.length; i++) {
for (z = 0; z < a.length; z++) {
if (a[i] === b[z]) {
finalArray.push(b[z]);
console.log(finalArray);
}
}
}
}
compareArrays();
無需使用嵌套循環和常規迭代。
數組過濾更加干凈,非常適合此操作:
const a = ["standard","industry","4578595"] const b = [{file:"server.log",value:"lorem ipsum industry standard 4578595"}, {file:"server.log",value:"lorem ipsum industry standadr"},{file:"server.log",value:"lorem ipsum industry"}]; const matchingCondition = ({ itemB, itemA }) => itemB.value.includes(itemA); // filter all items from B that satisfy a matching condition with at least one item from A const matches = b.filter( itemB => a.some( itemA => matchingCondition({ itemB, itemA }) ) ); console.log(matches);
// return a subset array of b, which contains all the strings of array a
var a = ["standard","industry","4578595"]
var b = [
{file:"server.log",value:"lorem ipsum industry standard 4578595"},
{file:"server.log",value:"lorem ipsum industry standadr"},
{file:"server.log",value:"lorem ipsum 4578595 industry"}];
function filterArray(a,b) {
var aLen = a.length;
var bLen = b.length;
var filterArray = []
// if a is empty it should return empty array
if (!aLen){
return filterArray;
}
for(var i = 0; i< bLen; i++) {
var bValuesArray = b[i].value.split(" ");
var bValuesLength = bValuesArray.length;
var addObject = 0;
for(var j=0; j< aLen; j++) {
for(var k=0; k <bValuesLength; k++ ){
if(a[j] === bValuesArray[k]){
addObject++;
continue;
}
}
}
// add if all elements of a are present in b array
if(addObject === aLen) {
filterArray.push(b[i]);
}
}
return filterArray;
};
console.log(filterArray(a,b));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.