-1

I have been trying to do the following:

var arr1 = ["A", "B"];

var arr2 = ["A", "B"];

// Where the result should be
var arrayOfObjects = [
  {
    arr1: "A",
    arr2: "A"
  },
  {
    arr1: "B",
    arr2: "B"
  }

];

Essentially I would like to sort out the arrays into objects. I don't know how else to explain in words. I could do this the long and hard way through looping. I am used to this kind of programming because I come from a long history of C and C++ programming. I would like some help figuring this out in a cleaner JS way.

Also if anyone can point me to a great reference for being able to solve problems like this in JS. I have tried looking at W3schools and the MDN but not enough examples are shown when looking up useful functions. Or maybe I just suck at reading the docs and would like references that help me to understand the docs.

A more specific example was asked:

var name = ["John", "Adam"];
var age = ["19","31"];

result = {
  {
      name: "John",
      age: "19"
  },
  {
      name: "Adam",
      age: "31"
  },
}

Also all arrays are the same length.

James Mak
  • 120
  • 1
  • 14
  • 1
    Can you provide a more complex test case? What if they're mismatched like `["A", "D"]` and `["B", "C"]` – Andrew Feb 14 '18 at 02:17
  • 2
    what about arrays with varying lengths? – manonthemat Feb 14 '18 at 02:19
  • In JavaScript it does have a function to sort array containing of just numbers or string, but with objects you will have to write your own object comparer to sort. Have a look at https://stackoverflow.com/questions/1129216/sort-array-of-objects-by-string-property-value-in-javascript – mylee Feb 14 '18 at 02:24
  • Please post the code with looping that you would have written, so that we a) know what it is supposed to do and b) have a baseline example to compare cleanliness. – Bergi Feb 14 '18 at 02:53
  • @mylee This question has nothing to do with sorting actually – Bergi Feb 14 '18 at 02:55
  • 1
    You're looking for [`zipWith`](https://stackoverflow.com/search?q=zipWith+[js]) functionality. – Bergi Feb 14 '18 at 02:58

1 Answers1

2

You could use Array.prototype.map(). Here's an example:

const arr1 = ['A', 'B', 'C', 'D']
const arr2 = ['A', 'B', 'C']

// use the map function on the array with the greater length i.e. arr1
// if length is equal, use either
const arrayOfObjects = arr1.map((element, i) => ({
  arr1: element,
  arr2: (i < arr2.length) ? arr2[i] : null // handle index out of bounds on arr2
}))

Process is not really sorting, but mapping an array of strings to an array of objects. Personally, I find the MDN docs the best reference for Javascript.

Jaye Renzo Montejo
  • 1,812
  • 2
  • 12
  • 25