skip to Main Content

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


  1. No need for a double loop, use the first array as source map() over it and check with includes if it’s in the second one

    const outerArray = ["apiAccessAdmin", "defg", "abcd"];
    const innerArray =["apiAccessAdmin", "abcd"];
    
    const res = outerArray.map(cname => ({ cname, checked: innerArray.includes(cname) }));
    console.log(res)
    Login or Signup to reply.
  2. For a real world program, you should use a Set as it provides constant O(1) lookups –

    const outerArray = ["apiAccessAdmin", "defg", "abcd"];
    const innerArray = ["apiAccessAdmin", "abcd"];
    
    const s = new Set(innerArray)
    const r = outerArray.map(cname => ({
      cname,
      checked: s.has(cname),
    }))
    
    
    console.log(r)
    Login or Signup to reply.
  3. Thinking outside the box as per usual…

    var A1 = ['apiAccessAdmin', 'defg', 'abcd'];
    var A2 = ['apiAccessAdmin', 'abcd'];
    let A3=A1.concat(A2);
    A3=Array.from(new Set(A3));
    for(let i=0; i<A3.length; i++){
      A3[i]={'cname': A3[i], 'checked': (A1.includes(A3[i]))&&(A2.includes(A3[i]))};
    }
    

    Testing…

    alert(A3[0].cname);
    alert(A3[0].checked);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search