pse
pse

Reputation: 151

Nested array not returning correct data

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.

Upvotes: 2

Views: 54

Answers (2)

Siva Kondapi Venkata
Siva Kondapi Venkata

Reputation: 11001

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);

Upvotes: 0

Harmandeep Singh Kalsi
Harmandeep Singh Kalsi

Reputation: 3345

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)

Upvotes: 1

Related Questions