2

I have an array that contains a bunch of objects:

let sample = [
  {
    name: 'obj1',
    values: ["value1", "value2"]
  },
  {
    name: 'obj2',
    values: ["value3", "value4"]
  },
  {
    name: 'obj3',
    values: ["value5", "value6"]
  }
]

I need to combine all the arrays on the objects to end up with something like this:

let outputArray = ["value1", "value2", "value3", "value4", "value5", "value6"]

Cant seem to find the best way to do this. Thank you.

5 Answers 5

3

You could use Array.flatMap to first map each object to its values array, and then flatten the result:

let sample = [
  {
    name: 'obj1',
    values: ["value1", "value2"]
  },
  {
    name: 'obj2',
    values: ["value3", "value4"]
  },
  {
    name: 'obj3',
    values: ["value5", "value6"]
  }
]

let outputArray = sample.flatMap(o => o.values);
console.log(outputArray);

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

Comments

1

In addition to Nick's answer, you can also use the reduce function for a wider range of support in different environments if you are not using tools like babel.

let sample = [
  {
    name: 'obj1',
    values: ["value1", "value2"]
  },
  {
    name: 'obj2',
    values: ["value3", "value4"]
  },
  {
    name: 'obj3',
    values: ["value5", "value6"]
  }
]

const result = sample.reduce((acc, item) => {
  return [...acc, ...item.values];
}, []);

console.log(result);

1 Comment

I think reduce should be slightly faster than flatMap too.
1

You could use Array.reduce along with Array.concat:

let sample = [
  {
    name: 'obj1',
    values: ["value1", "value2"]
  },
  {
    name: 'obj2',
    values: ["value3", "value4"]
  },
  {
    name: 'obj3',
    values: ["value5", "value6"]
  }
];

let valuesArray = sample.reduce((a, b) => a.concat(b['values']), []);
console.log(valuesArray);

Comments

0

I think what you want to employ is the array concat() method. This method does not change the existing arrays, but returns a new array, containing the values of the joined arrays.

My proposed solution:

const outputArray = sample[0].values.concat(sample[1].values, sample[2].values);

Comments

0
let outputArray=[]  
sample.forEach(item=> { outputArray.push(item.values.map(val=> val)) })

Comments

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.