max23701
max23701

Reputation: 279

Build array of 2 arrays using JAVASCRIPT REDUCE with one line using Ternary Operator

Suppose I have an array of objects

const companyList = [
    {
        name: 'amazon',
        isIntermediary: false
    },
    {
        name: 'microsoft',
        isIntermediary: false
    },
    {
        name: 'talentsearch',
        isIntermediary: true
    },
    {
        name: 'talent global',
        isIntermediary: true
    },
    {
        name: 'taleo',
        isIntermediary: true
    }
];

I want to create 2 arrays. I can do so using reduce

const companies = companyList.reduce(
    (acc, curr) => {
        if (!curr.isIntermediary) {
            acc[0].push(curr);
        } else {
            acc[1].push(curr);
        }
        return acc;
    },
    [[], []]
);

Is there a way to refactor this code to use Ternary Operator instead and have it being a one-liner? I'm struggling to do so... Thanks for help !

Upvotes: 0

Views: 62

Answers (3)

Tom Faltesek
Tom Faltesek

Reputation: 2818

It's not exactly the most readable one-liner, but I think it's what you've asked for.

const companyList = [{
    name: 'amazon',
    isIntermediary: false
  },
  {
    name: 'microsoft',
    isIntermediary: false
  },
  {
    name: 'talentsearch',
    isIntermediary: true
  },
  {
    name: 'talent global',
    isIntermediary: true
  },
  {
    name: 'taleo',
    isIntermediary: true
  }
];

const companies = companyList.reduce((acc, c) => c.isIntermediary ? [acc[0], [...acc[1], c]] : [[...acc[0], c], acc[1]], [[], []]);

console.log(companies)

Upvotes: 0

Dominik Matis
Dominik Matis

Reputation: 2146

By your code, this is what you want (using ternary to choose whether index 0 or 1)

const companyList = [
    {
        name: 'amazon',
        isIntermediary: false
    },
    {
        name: 'microsoft',
        isIntermediary: false
    },
    {
        name: 'talentsearch',
        isIntermediary: true
    },
    {
        name: 'talent global',
        isIntermediary: true
    },
    {
        name: 'taleo',
        isIntermediary: true
    }
];

const companies = companyList.reduce(
    (acc, curr) => [!curr.isIntermediary ? [...acc[0], curr] : [...acc[0]], curr.isIntermediary ? [...acc[1], curr] : [...acc[1]]],
    [[], []]
);

console.log(companies)

Upvotes: 0

Slai
Slai

Reputation: 22876

Boolean converted to Number becomes 0 or 1, and comma operator can be used to shorten it :

const companyList = [ { name: 'amazon',        isIntermediary: false },
                      { name: 'microsoft',     isIntermediary: false },
                      { name: 'talentsearch',  isIntermediary: true  },
                      { name: 'talent global', isIntermediary: true  },
                      { name: 'taleo',         isIntermediary: true  } ]
                      
const companies = companyList.reduce((a, v) => (a[+v.isIntermediary].push(v), a), [[], []])

console.log(companies)

Upvotes: 3

Related Questions