Home > Blockchain >  How to prevent For loop from producing duplicates of the same result of array?
How to prevent For loop from producing duplicates of the same result of array?

Time:07-18

I have two arrays, one is a list of names, and one is a list of age that is generated with a function. To make things easier, i'll just show the final result of the two arrays.

let nameList=["John","Brenda","Sabrina","Ray","Jacob"];
let ageList=[ 23, 29, 30, 23, 25 ]

I wanted to create a new array where i can combine each name paired with the age number of the same sequence. Ex: John will have 23 next to it, Brenda 29, Sabrina 30, and so on.

I have written this function to do it

function combineData (nameArray,ageArray,combArray){
    let tempComb=[];
    for (let i=0;i<nameArray.length;i  ) {
        tempComb.push(nameArray[i]);
        tempComb.push(ageArray[i]);
        combArray.push(tempComb);
    }
}

The result of this loop kinda did what i wanted to get, but not really. Below is the result it returns

[ [ 'John', 23, 'Brenda', 29, 'Sabrina', 30, 'Ray', 23, 'Jacob', 25 ],
  [ 'John', 23, 'Brenda', 29, 'Sabrina', 30, 'Ray', 23, 'Jacob', 25 ],
  [ 'John', 23, 'Brenda', 29, 'Sabrina', 30, 'Ray', 23, 'Jacob', 25 ],
  [ 'John', 23, 'Brenda', 29, 'Sabrina', 30, 'Ray', 23, 'Jacob', 25 ],
  [ 'John', 23, 'Brenda', 29, 'Sabrina', 30, 'Ray', 23, 'Jacob', 25 ] ]

can anybody tell me how to prevent it from duplicating?

Extra question. Is there a way to put each name & age pairing into their own array and then combine it with the others which will create a nested array like this?

[['John', 23],['Brenda',29],['Sabrina',30],['Ray',23],['Jacob',25]]

CodePudding user response:

You can map over the names and use the index to add the element from the ages array.

const nameList = [ 'John', 'Brenda', 'Sabrina', 'Ray', 'Jacob' ];
const ageList = [ 23, 29, 30, 23, 25 ];

const out = nameList.map((name, i) => {
  return [name, ageList[i]];
});

console.log(out);

CodePudding user response:

This is a one liner in various underscore like libraries. The function usually called zip.

const results = _.zip(nameList, ageList)

CodePudding user response:

const nameList = ["John", "Brenda", "Sabrina", "Ray", "Jacob"];
const ageList = [23, 29, 30, 23, 25];

function zipper(arr1, arr2) {
  const temp = {};
  for (let i = 0; i < arr1.length; i  ) {
    temp[arr1[i]] = arr2[i];
  }
  return Object.entries(temp);
}
  • Related