It's All Writing.

Writing makes you happy.

How to detect that it can be merged between multiple elements in an array at node.

Prerequisites

There are arrays has multiple elements as below.

const mergeableArray = [
  {
    'age': 18,
    'status': true
  },
  {
    'hobby': 'fishing'
  },
  {
    'status': null
  }
];

const unmergeableArray = [
  {
    'age': 18,
    'status': true
  },
  {
    'hobby': 'fishing'
  },
  {
    'age': 24,
    'status': null
  }
];

Environment

  • node
  • lodash

Code

const lodash = require('lodash');

console.log(isMergeableArray(mergeableArray));
// => true

console.log(isMergeableArray(unmergeableArray));
// => false

function isMergeableArray(array) {
  let is_mergeable = true;
  let result = array.reduce(function(res, obj){
    Object.keys(obj).forEach(function(k){
      res[k] = res[k] || [];
      res[k] = res[k].concat(obj[k]);
      res[k] = lodash(res[k]).uniq().compact().value();
   });
   return res;
  },{});
  lodash.pickBy(result, (item, key) => {
    if (item.length > 1) {
      is_mergeable = false;
    } else {
      // do nothing...
    }
  });
  return is_mergeable;
}

If you want to distinguish difference of falsy values(false, null, 0, "", undefined, and NaN), you can use code as below.

const lodash = require('lodash');

console.log(isMergeableArray(mergeableArray));
// => false ( cause this code distinguish status: true and status: null. )

console.log(isMergeableArray(unmergeableArray));
// => false

function isMergeableArray(array) {
  let is_mergeable = true;
  let result = array.reduce(function(res, obj){
    Object.keys(obj).forEach(function(k){
      res[k] = res[k] || [];
      res[k] = res[k].concat(obj[k]);
      res[k] = lodash(res[k]).uniq().value(); // <= remove compact()
   });
   return res;
  },{});
  lodash.pickBy(result, (item, key) => {
    if (item.length > 1) {
      is_mergeable = false;
    } else {
      // do nothing...
    }
  });
  return is_mergeable;
}