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

112
Views
array of arrays conversion in Javascript

I need to create an array of array. It is worth noting that the database is very large and that if any attribute does not have a corresponding value, it sends an empty string. I've tried with map and reduce but I wasn't successful:

Any help will be appreciated.

Below I show an example of the expected output:

outputExpected = [
  ["id", 1, 2],
  ["name", "name1", "name2"],
  ["price", 6.95, 998.95],
  ["promoPrice", 5.91, 333.91],
  ["category", "test1 | test2", "test3 | test4"],
]

Any way to solve this problem performatically?

this is my code:

let arrayObj = [{
    "id": 1,
    "name": "name1",
    "price": 6.95,
    "promoPrice": 5.91,
    "category": ["test1, test2"]
  },
  {
    "id": 2,
    "name": "name2",
    "price": 998.95,
    "promoPrice": 333.91,
    "category": ["test3, test4"]
  }
]

const headers = ["id", "name", "price", "promoPrice", "category"]
const result1 = headers.concat(arrayObj.map((obj) => {
  return headers.reduce((arr, key) => {
    arr.push(obj[key]) return arr;
  }, [])
}))

console.log(result1)

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

Reduce the array to a Map. On each iteration convert the object to an array of [key, value] pairs using Object.entries(). Use Array.forEach() to iterate the entries and add them to the map. Convert the Map's values iterator to an array using Array.from():

const arr = [{"id":1,"name":"name1","price":6.95,"promoPrice":5.91,"category":["test1", "test2"]},{"id":2,"name":"name2","price":998.95,"promoPrice":333.91,"category":["test3", "test4"]}]

const result = Array.from(arr.reduce((acc, o) => {
  Object.entries(o)
    .forEach(([k, v]) => {
      if(!acc.has(k)) acc.set(k, [k])
      
      acc.get(k).push(Array.isArray(v) ? v.join(' | ') : v)
    })
  
  return acc
}, new Map()).values())

console.log(result)

about 4 years ago · Juan Pablo Isaza Report

0

You could simply map the value and check if an item is an array, then take the joined values or the value itself.

const
    data = [{ id: 1, name: "name1", price: 6.95, promoPrice: 5.91, category: ["test1, test2"] }, { id: 2, name: "name2", price: 998.95, promoPrice: 333.91, category: ["test3, test4"] }],
    headers = ["id", "name", "price", "promoPrice", "category"],
    result = data
        .reduce(
            (r, o) => headers.map((k, i) => [
                ...r[i],
                Array.isArray(o[k]) ? o[k].join(' | ') : o[k]
            ]),
            headers.map(k => [k]),
        );

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

about 4 years ago · Juan Pablo Isaza Report

0

construct one init array with all possible keys with the wanted order, then uses Array.reduce and Array.forEach to Array.push value for per key based on its index.

const arrayObj = [
  {
  "id":1,
  "name":"name1",
  "price":6.95,
  "promoPrice":5.91,
  "category":["test1", "test2"]
  },
  {
    "id":2,
    "name":"name2",
    "price":998.95,
    "promoPrice":333.91,
    "category":["test3", "test4"]
  }
]

function ConvertToArray2D (items) {
  let init = [['id'], ['name'], ['price'], ['promoPrice'], ['category']]
  if (!items) return init
  return arrayObj.reduce((pre, cur) => {
    init.forEach((key, index) => {
      pre[index].push(Array.isArray(cur[key[0]]) ? cur[key[0]].join('|') : cur[key[0]])
    })
    return pre
  }, init.slice())
}
console.log(ConvertToArray2D(arrayObj))

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!