Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

185
Views
I want to create an object from an array which has subarray also

This is my input:

const arr =  [10,20,[40,50,60],70,80,[90,100],111,112];

output what I want:

{10:10,20:20,'array1':{40:40,50:50,60:60},70:70,80:80,'array2':{90:90,100:100},111:111,112:112}
about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

my approach using Array.prototype.reduce(). only handles 1 level nested array.

const arr =  [10,20,[40,50,60],70,80,[90,100],111,112];
let count=1;

let a = arr.reduce((acc,curr) => {

    if(Array.isArray(curr)){
    let b = curr.reduce((acc1,curr1)=> {
        acc1[curr1] = curr1;
      return acc1
    },{})
    acc[`array${count}`] = b;
    count+=1;
  }
  else{
    acc[curr] = curr;
  }
 
  return acc;

},{})

console.log(a)

Since it is an object it necessarily doesn't have to be in the order you have given.

about 4 years ago · Juan Pablo Isaza Report

0

Here a recursive solution with reduce(), which also works for deeper nested arrays if you need that.

function foo(array){
    let arrCounter=0;
    return array.reduce((acc,curr)=>{
        if(!Array.isArray(curr)) acc[curr]=curr
        else{ arrCounter+=1;
            acc[`array${arrCounter}`]=foo(curr)        
        }
        return acc;
    },{})
} 

const arr =  [10,20,[40,50,60],70,80,[90,100],111,112];
console.log(foo(arr));

const deepArr =  [10,20,[40,50,60],70,80,[90,100,[40,50,60]],111,112];
console.log(foo(deepArr));

about 4 years ago · Juan Pablo Isaza Report

0

Simply loop through the array, formatting a new object as you go:

let array_count = 1;
let obj = {}

arr.forEach((el) => {
  if(Number.isInteger(el)){
    obj[el] = el;
  } else {
    inline_obj = {}
    el.forEach((e2) => inline_obj[e2] = e2);
    obj[`array${array_count}`] = inline_obj;
    array_count += 1;
  }
})
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!