Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

174
Views
How do I make the first half of the values of an array become keys, and the other half to become values of those keys?

I have the following:

const array = [{value: 'banana'}, {value: 'apple'}, {value: 'yellow'}, {value: 'red'}]

I need the following:

const result = [{banana: 'yellow'}, {apple: 'red'}];

Is there a way to create result from the array, using loops or higher-order-functions in JavaScript?

about 4 years ago ยท Juan Pablo Isaza
2 answers
Answer question

0

You can use Array.prototype.flatMap:

const flatMapToEntry = (key, index, array) => {
  const length = array.length / 2;
  if (index >= length) {
    return [];
  }
  const value = array[index + length];
  return [{ [key]: value }];
};
const result = array.map(o => o.value).flatMap(flapMapToEntry);
about 4 years ago ยท Juan Pablo Isaza Report

0

Here is an answer using the same logic provided in the comment. This has relevant descriptions to help understand better.

const getMyObject = arr => {
  // first compuate the half-length "lenBy2" of given array
  const lenBy2 = Math.floor(arr.length / 2);
  
  // return the "result" as an object
  return Object
    .fromEntries(                 // generate object from key-value pairs below
      arr.map(                    // iterate "arr" to obtain key-value pairs
        ({ value }, idx) => (     // get the index "idx" and de-structure to access "value"
          idx < lenBy2            // if index less than half-length "lenBy2"
          ? [                     // return key-value pair as a 2-element array
            value,                // [ "banana", "yellow" ], for example
            arr[idx + lenBy2]?.value
          ]
          : []                    // if index >= half-length, return empty array
        )
      ).filter(                   // filter key-value pairs to retain only non-empty ones
        x => x.length == 2
      )
    );
};

// below are steps only to generate results for various test cases
// the original array from the question
const array1 = [{value: 'banana'}, {value: 'apple'}, {value: 'yellow'}, {value: 'red'}];

// test-case 2 - an array with 3 pairs
const array2 = [
  {value: 'banana'}, {value: 'apple'}, {value: 'tomato'},
  {value: 'yellow'}, {value: 'green'}, {value: 'red'}
];

// mismatched array where the fruit "orange" has no matching color
const array3 = [
  {value: 'banana'}, {value: 'apple'}, {value: 'orange'},
  {value: 'yellow'}, {value: 'red'}
];

// mismatched array where the color "orange" has no matching fruit
const array4 = [
  {value: 'banana'}, {value: 'apple'},
  {value: 'yellow'}, {value: 'red'}, {value: 'orange'}
];

// iterate over the various test case arrays &
// console.log the result
[array1, array2, array3, array4].forEach((arr, idx) =>
  console.log(
    `\n***---> test case ${idx + 1} <---***\n`,
    'given array: ๐Ÿ‘‰ ', JSON.stringify(arr),
    '\n\nresult object: ๐Ÿ‘‡ \n', getMyObject(arr),
    '\n ***---> end of result <---*** \n\n'
  )
);
.as-console-wrapper { max-height: 100% !important; top: 0 }

Feel free to post questions in comments, in case it is unclear how the above works.

about 4 years ago ยท Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
ยฉ 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!