I have two Array as mentioned below:
const outerArray = ["apiAccessAdmin", "defg", "abcd"];
const innerArray =["apiAccessAdmin", "abcd"];
I need to iterate both the arrays and create a new one like below:
[{"cname":"apiAccessAdmin","checked":true},{"cname":"defg","checked":false},{"cname":"abcd","checked":true}]
Property "checked" will be true if elements present in both array. Anything not in innerArray and available in outerArray, "checked" property to be false.
I have tried this which is working but looking for some other approach to achieve this:
const innerArray =["apiAccessAdmin", "abcd"];
const finalArr =[];
for (var j = 0; j < outerArray.length; j++){
var isTrue = true;
for (var i = 0; i < innerArray.length; i++) {
if (outerArray[j] == innerArray[i]) {
finalArr.push({"cname": outerArray[j], "checked": true})
isTrue = false;
break;
}
}
if(isTrue){
finalArr.push({"cname": outerArray[j], "checked": false})
}
}
console.log("Output "+JSON.stringify(finalArr))
3
Answers
No need for a double loop, use the first array as source
map()
over it and check withincludes
if it’s in the second oneFor a real world program, you should use a
Set
as it provides constant O(1) lookups –Thinking outside the box as per usual…
Testing…