2

I am trying the nested array, can you help me with the loop, the code is not optimized and i need some guidance. I have 2 arrays, i am not getting the expected results.

let arr1 = ['a','b','c','d','e'];
let arr2 = ['b','e','f'];
var temp = arr2
  for(i =0; i< arr1.length; i++){
    for(j=0; j<arr2.length; j++){
      var flag = false;
      if(arr1[i] === arr2[j]){
        flag = true;
      }
      if(arr2.length -1 === j){
        if(flag == false){
          temp.push(arr1[i])
        }
        if( arr1.length - 1 == i){
              console.log(temp)
        }
      }
    }
  }

What i am trying to achieve is, from the second array i want output in this format

temp = ['b','e','f','a','c','d']

The elements which are not present in arr1 should be pushed to arr2 elements. I apologize for the beginner's code. I am still learning. Thank you.

2
  • 2
    temp is a pointer to arr2, so changes to temp are changes to arr2. to avoid that, use: temp=arr2.slice(), which will make a copy, instead. Commented Jul 11, 2020 at 15:52
  • @iAmOren Oh thanks for explaining, i was wondering why i was getting duplicates in the output (temp) Commented Jul 11, 2020 at 17:32

2 Answers 2

1

The solution will be easy , if you use array.forEach and array.includes methods .

  1. Then loop over arr1 and check if the element is not in arr2 , only then push it.

let arr1 = ['a','b','c','d','e'];
let arr2 = ['b','e','f'];



arr1.forEach(obj => {
 if(!arr2.includes(obj))
    arr2.push(obj);
})

console.log(arr2)

Sign up to request clarification or add additional context in comments.

Comments

0

let arr1 = ["a", "b", "c", "d", "e"];
let arr2 = ["b", "e", "f"];

// Method 1, using `reduce` and `includes`
const output1 = arr1.reduce(
  (acc, cur) => (!acc.includes(cur) && acc.push(cur), acc),
  arr2
);

// Method 2, using `reduce` and building object to handle duplicates. This will make look up easy
const output2 = Object.keys(
  arr2.concat(arr1).reduce((acc, cur) => Object.assign(acc, { [cur]: 1 }), {})
);

console.log(output1);
console.log(output2);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.