1

I have 2 arrays that i want to "reduce" into 1 object.

so for instance:

I have..

var originalData = [1,2,3];

var newData = [3,1,2];

i want to combine these two arrays into an object that looks like this:

var newOrderObject = {1:3, 2:1, 3:2};

im using a reduce function but it seems to be mapping them differently

var newOrderObject = originalData.reduce(function(newData) {
  var orderObject = {};
  originalData = newData;
  return orderObject;
}, {});

any suggests would be appretiated

3

3 Answers 3

6

Reduce the 1st array (the keys), and take the values from the 2nd array using the index:

var originalData = [1,2,3];
var newData = [3,1,2];

var newOrderObject = originalData.reduce(function(obj, key, index) {
  obj[key] = newData[index];
  return obj;
}, {});

console.log(newOrderObject);

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

Comments

3

You're just using .reduce wrong.

  • The 1st argument of it's callback is the accumulator object you pass.
  • The 2nd is the currently iterated item.
  • The 3rd is the index.

Use all 3 and you get the result you want.

var originalData = [1,2,3];
var newData = [3,1,2];

var newOrderObject = originalData.reduce(function(acc, item, i) {
  return Object.assign(acc, { [item]: newData[i] })
}, {});

console.log(newOrderObject)

Comments

3

You could map single objects and assign them to a single object. If empty arrays are possible, use an empty object as target value.

var keys = [1, 2, 3],
    values = [3, 1, 2],
    object = Object.assign({}, ...keys.map((k, i) => ({ [k]: values[i] })));

console.log(object);

A more cleaner approach would be to transpose the arrays to an array of key/value pairs and then map object.

const transpose = (r, a) => a.map((v, i) => (r[i] || []).concat(v));

var keys = [1, 2, 3],
    values = [3, 1, 2],
    object = Object.assign(
        {},
        ...[keys, values]
            .reduce(transpose, [])
            .map(([k, v]) => ({ [k]: v }))
    );

console.log(object);

1 Comment

@Shidersz, with an empty object as target object, it works with empty arrays.

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.