Home > Net >  Merge arrays in javascript using only loops without any methods
Merge arrays in javascript using only loops without any methods

Time:03-29

I am a newbie to coding. I have a question and looking for help. SO, I want to merge two arrays with some common elements to both. I want the output with elements of both arrays removing the duplicates without using any array methods as shown below:

var array1 = [1,4,6,7,3,8,9,2,10,11,5,19,20]; var array2 = [5,37,11,23,20,15,6,1,91];

var output = [1,2,3,4,5,6,7,8,9,10,11,15,19,20,23,37,91]

I tried something like this:

    var array1 = [1,4,6,7,3,8,9,2,10,11,5,19,20];  //4,7,3,8,9,2,10,19 only in array1
    var array2 = [5,37,11,23,20,15,6,1,41];        //37,23,15,41 only in array2
    var common = [];                              //should be [1,6,11,5,20]
    var different = [];                           //should be [4,7,3,8,9,2,10,19,37,23,15,41]

    for (i=0; i<=(array1.length-1); i  )
    {
        for(j=0; j<=(array2.length-1); j  )
        {
            if (array1[i] == array2[j])
            {
                common[i] = array1[i];
                break;                
            }       
        }

        for(j=0; j<=(array2.length-1); j  )
        {
            if ((array1[i] != array2[j]) && (array1[i] == common[i]))
            {
                continue;
            }
            else if ((array1[i] == array2[j]) && (array1[i] == common[i]))
            {
                continue;
            }
            else if ((array1[i] == array2[j]) && (array1[i] != common[i]))
            {
                common[i] = array1[i];
            }   
            else if ((array1[i] != array2[j]) && (array1[i] == different[i]))
            {
                continue;
            }
            else if ((array1[i] != array2[j]) && (array1[i] != different[i]))
            {
                different[i] = array1[i];
            }
        }
    }
    console.log(common);
    console.log(different);

with above code, I got the result something like this:

Expected result: array common = [1,6,11,5,20] array different = [4,7,3,8,9,2,10,19,37,23,15,41]

Actual result: array common : [1, empty, 6, empty × 6, 11, 5, empty, 20] (have to remove the empty spaces too) array different : [empty, 4, empty, 7, 3, 8, 9, 2, 10, empty × 2, 19]

Now, I need to merge these two resultant arrays too.

// same with no empty spaces in resultant array of same elements

    var array1 = [1,4,6,7,3,8,9,2,10,11,5,19,20];
    var array2 = [5,37,11,23,20,15,6,1,91];
    var common = [];
    var different = [];

    for (i=0; i<=(array1.length-1); i  )
    {
        for (j=0; j<=(array2.length-1); j  )
        {
            if ((array1[i] == array2[j]) && (array1[i] != common[i]))
            {
                common[common.length] = array1[i];               
            }
            else if ((array1[i] == array2[j]) && (array1[i] == common[i]))
            {
                break;               
            }
        }
    }
    console.log(common);
    console.log(different);

tried to remove the empty spaces, and I got the result for an array of common elements but could not do it for the other array:

Actual result: array common : [1, 6, 11, 5, 20]

Can someone please help me with this?

CodePudding user response:

Use concat to merge two arrays. You can make a set of this to remove the duplicates.

    var array1 = [1,4,6,7,3,8,9,2,10,11,5,19,20];  //4,7,3,8,9,2,10,19 only in array1
    var array2 = [5,37,11,23,20,15,6,1,41];

    let unique = [...new Set(array1.concat(array2))];
    
    console.log(unique)

CodePudding user response:

Okay, we're not allowed to use array methods, but maybe we could use object methods?

const array1 = [1,4,6,7,3,8,9,2,10,11,5,19,20]; 
const array2 = [5,37,11,23,20,15,6,1,41]; 

const addArray = (arr, obj = {}) => {
  for (i=0; i<=(arr.length-1); i  = 1) {
    obj[arr[i]] = true;
  };
  return obj;
}


// --- unique

let obj1 = addArray(array1);
obj1 = addArray(array2, obj1);
const unique = Object.keys(obj1);

console.log('unique:', ...unique);


// --- commons

const obj2 = addArray(array1);
const commonObj = {};

for (i=0; i<=(array2.length-1); i  = 1) {
  if (obj2[array2[i]]) commonObj[array2[i]] = true;
};
const commons = Object.keys(commonObj);  

console.log('commons:', ...commons);


// --- differents 

const obj3 = addArray(array1);
const differentObj = {};

for (i=0; i<=(array2.length-1); i  = 1) {
  if (!obj3[array2[i]]) differentObj[array2[i]] = true;
};
const differents = Object.keys(differentObj);  

console.log('differents:', ...differents);
.as-console-wrapper{min-height: 100%!important; top: 0}

CodePudding user response:

As I understood it, you wanted to remove any form of duplicates, and never add them to the end array, but you then wanted to merge the duplicates with the unique values in the end.

So all in all, you want to end up with an array that only has unique values.


I'm using an object to keep track if the value is added to the array. I also broke down the code with a helper method so I could add more arrays as parameters without any hassle.

I finally returned both the end result—as an array—but also the object.

I did some trickery with the return values, but I think you can understand what it does just by looking at it. It's called Destructuring assignment if you want to read more about it.

var array1 = [1, 4, 6, 7, 3, 8, 9, 2, 10, 11, 5, 19, 20]; //4,7,3,8,9,2,10,19 only in array1
var array2 = [5, 37, 11, 23, 20, 15, 6, 1, 41]; //37,23,15,41 only in array2

function mergeUniqueValues(arr1, arr2) {
  let uniqueArr = [];
  let checkDuplicateObj = {};

  [uniqueArr, checkDuplicateObj] = helper(arr1, uniqueArr, checkDuplicateObj);
  [uniqueArr, checkDuplicateObj] = helper(arr2, uniqueArr, checkDuplicateObj);

  return [uniqueArr, checkDuplicateObj];
}

function helper(arr, uniqueArr, checkDuplicateObj) {
  for (let value of arr) {
    if (checkDuplicateObj[value]) {
      checkDuplicateObj[value]  ;
    } else {
      uniqueArr[uniqueArr.length] = value; // same as uniqueArr.push(value);
      checkDuplicateObj[value] = 1;
    }
  }
  
  return [uniqueArr, checkDuplicateObj];
}

let [uniques, checkDuplicateObj] = mergeUniqueValues(array1, array2);

console.log({uniques}); // [1, 4, 6, 7, 3, 8, 9, 2, 10, 11, 5, 19, 20, 37, 23, 15, 41]

  • Related