0

I have two arrays:

let names1 = ["om","karan","ranjett","rocky"] <br>
let names2 = ["vaibhu","Shrushti","rekha","kunal"]

How do you iterate over both arrays and makes a new object. Get one element from names1 also from names2 and one random number and push these into an object

eg:-

obj = {

{

n1:"om" n2: "vaibhu" randomnumber:12 },

//remaining array

}

KoderM
3822 silver badges15 bronze badges
asked Jul 7, 2022 at 14:58
2
  • 1
    "I want a code", this isn;t a free coding service. Please see How to Ask. Show us your attempt Commented Jul 7, 2022 at 14:59
  • I believe you should consider the structure of your data. Iterating over 2 arrays considering they have the same length, would be risky. Commented Jul 7, 2022 at 15:15

1 Answer 1

1

Just map over it?

let names1 = ["om","karan","ranjett","rocky"]
let names2 = ["vaibhu","Shrushti","rekha","kunal"]
const combined = names1.map((item, index) => ({
 n1: item,
 n2: names2[index],
 randomnumber: Math.ceil(Math.random() * 100)
}));
console.log(combined);
/*
[
 { n1: 'om', n2: 'vaibhu', randomnumber: 49 },
 { n1: 'karan', n2: 'Shrushti', randomnumber: 87 },
 { n1: 'ranjett', n2: 'rekha', randomnumber: 1 },
 { n1: 'rocky', n2: 'kunal', randomnumber: 74 }
]
*/
answered Jul 7, 2022 at 15:02
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.