2

How to create array of object from two different length of array

for example

arr1 = ["first","second","third","fourth","fifth","Sixth"]
arr2 = [["1","2","3","4","5","6"],["7","8","9","10","11","12"],["1","2","3","4"]]

finalArray = [{
   first:1,
   second:2
   third:3,
   fourth:4,
   fifth:5,
   sixth:6
},{
   first:7,
   second:8
   third:9,
   fourth:10,
   fifth:11,
   sixth:12
}]

I tried this using map but getting every key value pair as whole object

example

[
 {first: 1}
 {second: 2}
 {third: 3}
 {fourth: 4}
]
0

3 Answers 3

4

With map() and reduce():

const arr1 = ["first", "second", "third", "fourth", "fifth", "Sixth"];
const arr2 = [["1", "2", "3", "4", "5", "6"],
              ["7", "8", "9", "10", "11", "12"],
              ["1", "2", "3", "4"]];

const res = arr2.map(v => v.reduce((a, v, i) => ({...a, [arr1[i]]: v}), {}));

console.log(res);

Sign up to request clarification or add additional context in comments.

4 Comments

I feel this is a bad approach because it has poor runtime complexity: you're using the spread-operator (which will perform an O(n) array copy on every input element) in reduce.
@Dai You are correct, but for small data volumes the difference will be negligible, and if we were aiming for optimal runtime performance, we would not be using any of the array functions like map() or reduce() anyway. Another thing worth mentioning is that we don't know what optimizations the JavaScript engine introduces, so it's hard to determine actual runtime complexity. With no stipulations about performance requirements in the question, I err on the side of conciseness and readability.
So what could be the best approach beside any predefined function @RobbyCornelissen
Iterate using only for loops, regular property assignments to objects, push to add to array.
0

You can take advantage of Array.prototype.reduce to update the shape of the result array

let arr1 = ["first","second","third","fourth","fifth","Sixth"];
let arr2 = [["1","2","3","4","5","6"],["7","8","9","10","11","12"],["1","2","3","4"]];

let result = arr2.reduce((accumulator, current) => {
  let obj = arr1.reduce((acc, currentKey, index) => {
    if(current.indexOf(index) && current[index] !== undefined ){
      acc[[currentKey]] = current[index];
    }
    return acc;
  }, {});
  return accumulator.concat(obj);
}, []);

console.log(result);

Comments

0

without reduce() and covered edge case when the arr1 contains fewer elements as the element from arr2

const arr1 = ["first","second","third","fourth","fifth","Sixth"]
const arr2 = [["1","2","3","4","5","6"],["7","8","9","10","11","12"],["1","2","3","4"]]

const res = arr2.map(values => {
    const res = {}
    for(const [index, value] of arr1.entries()){
        if(values[index]) {
            res[value] = values[index] // or parseInt(values[index])
        } else {
            break
        }
    }
    return res
})

console.dir(res)

1 Comment

if(values[index]) { - there's a bug here: if the values[index] value is falsy (e.g. 0) then your for loop will break too early.

Your Answer

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.