2

Reduce method is not easy, help me with this problem pls.

i need a function, that receive array with anything, and returns object with fields

{field1, field2, field3, field4}

like in the example: Input:

[true,6,'wow','you are smart, bro']

Output:

{field1: true, field2:1, field3: 'wow', field4: 'you are smart, bro'}

1
  • can you line out what you've tried already ? Commented Mar 14, 2020 at 23:02

5 Answers 5

7

A solution that uses Object.fromEntries (browsers that support ECMAScript 2019 only):

const arr = [true, 6, 'wow', 'you are smart, bro'];

const result = Object.fromEntries(arr.map((x, i) => [`field${i + 1}`, x]));

console.log(result);

A solution that uses Array.prototype.reduce and ECMAScript 2015:

const arr = [true, 6, 'wow', 'you are smart, bro'];

const result = arr.reduce((acc, cur, i) => ({ ...acc, [(`field${i + 1}`)]: cur }), {});

console.log(result);

And a solution that uses Array.prototype.reduce and ECMAScript 5 (browsers as old as IE11):

var arr = [true, 6, 'wow', 'you are smart, bro'];

var result = arr.reduce(function(acc, cur, i) {
    acc['field' + (i + 1)] = cur;
    return acc;
}, {});

console.log(result);

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

Comments

6

Solution

const arr = [true,1,'wow','you are smart, bro']

const f = (acc, rec, index) => {
  acc[`field${index + 1}`] = rec //
  return acc
}

const result = arr.reduce(f, {})
console.log(result)

Explanation

I extracted the callback function into f variable for readability's sake.

The callback function expects the following input: accumulator acc to store the results in, the value of the current processed element rec, and index.

const f = (acc, rec, index) => {...}

The index is optional but we need to get array indexes anyway to use them in our resulting object's keys. We know that array's index count starts from 0 and not from 1, so we have to add + 1 to the count to get field1 key instead of field0.

I chose to use string interpolation to get the necessary result:

`field${index + 1}`

Then we assign the corresponding array element to the object under the key we've just constructed:

acc[`field${index + 1}`] = rec

The reduce function expects the following input: callback (function f ) and initial value, which here should be an empty object {}, since we need to have an object as result.

reduce(f, {})

Now we create new variable result which will be the output of the reduce function on each element of the array arr:

const result = arr.reduce(f, {})

2 Comments

Its always great to have an answer but including an explanation of how you fixed it is amazing!
Thanks for the tip @mw509 I've just updated my answer and added some explanation.
2

const arr = [true,6,'wow','you are smart, bro'] 
const obj  = arr.reduce(
  (acc, rec, index) => ({ ...acc, [`field${index + 1}`]: rec }),
  {}
)

console.log(obj) 
You need always remember that index start from 0

Comments

1

const result = [true,6,'wow','you are smart, bro']
.reduce((acc, rec, i) => ({...acc, [`field${i + 1}`]: rec}),{})


console.log(result)

Comments

1

const database = [true, 1, "wow", "you are smart, bro"];

const result = (arr) => arr.reduce(
  (acc, rec, i) => ({
    ...acc, 
    [`field${i + 1}`]: rec
  }),
  {}
);

console.log(result(database));

1 step:

acc(0 elements) + field{0+1}: true
     |
 accumulator is empty

2 step:

acc(1 element) + field{1+1}: 1
     |
 field1: true

3 step:

acc(2 elements) + field{2+1}: "wow"
     |
 field1: true
 field2: 1

4 step:

acc(3 elements) + field{3+1}: "you are smart, bro"
     |
 field1: true
 field2: 1
 field3: "wow"

end:

 field1: true
 field2: 1
 field3: "wow"
 field4: "you are smart, bro"

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.