Combine 2 lists into one using map & arrow function

Related searches

I have 2 lists and I want to combine them so that I can populate them into a list. I know this can be done using nested for loops but, I'm trying to avoid for loops because of the amount of data I'll have to loop on. I would like to achieve this using the arrow functions or anything else.

List One:

let fields = [
    {
        field: "Name",
        fieldType: "Text"
    },
    {
        field: "Active__c",
        fieldType: "Boolean"
    },
    {
        field: "Contact",
        fieldType: "Relationship"
    }
];

List Two:

let rows = [
    {
        contact: {
            Name: "Joe",
            Active__c: true,
            Contact: "SomeContact"
        }
    },
    {
        contact: {
            Name: "Rachel",
            Active__c: true
        }
    },
    {
        contact: {
            Name: "Ross",
            Active__c: true
        }
    },
    {
        contact: {
            Name: "Monica",
            Active__c: true
        }
    }
];

Current code:

let output = rows.map(row => ({
    id: row.Id,
    data: {
        value: fields.map(field => (row.contact[field.field])),
        field: fields.map(field => field.field)
    }
}));

The output of this code:

[
    {
        "data": {
            "value": [
                "Joe",
                true,
                "SomeContact"
            ],
            "field": [
                "Name",
                "Active__c",
                "Contact"
            ]
        }
    },
    {
        "data": {
            "value": [
                "Rachel",
                true,
                null
            ],
            "field": [
                "Name",
                "Active__c",
                "Contact"
            ]
        }
    },
    {
        "data": {
            "value": [
                "Ross",
                true,
                null
            ],
            "field": [
                "Name",
                "Active__c",
                "Contact"
            ]
        }
    },
    {
        "data": {
            "value": [
                "Monica",
                true,
                null
            ],
            "field": [
                "Name",
                "Active__c",
                "Contact"
            ]
        }
    }
]

Desired output:

[
    data : [
        [
            {
                field : "Name",
                type: "Text",
                value : "Joe"
            },
            {
                field : "Active__c",
                type: "Boolean",
                value : true
            },
            {
                field : "Contact",
                type: "Relationship",
                value : "SomeContact"
            }
        ],
        [
            {
                field : "Name",
                type: "Text",
                value : "Rachel"
            },
            {
                field : "Active__c",
                type: "Boolean",
                value : false
            },
            {
                field : "Contact",
                type: "Relationship",
                value : "SomeContact Two"
            }
        ],
        [
            ...
        ],
        [
            ...
        ]
    ]
]

How can I achieve this?


The data property is unique and it has to be defined inline creating an object (not an array as you have in your desired output). You have to map fields array to each element of rows and then fill each field data with the row data if they exist. Also, I can't see an Id field on any row object inside rows array. This code sets null if a field does not exists:

let output = {
  data: rows.map(({ contact }) => 
    fields.map(({ field, fieldType: type }) => ({
      field,
      type,
      value: field in contact ? contact[field] : null // Set null if contact has no field
    }))
  )
}

Run this code snippet to see the results:

let fields = [
  {
    field: "Name",
    fieldType: "Text"
  },
  {
    field: "Active__c",
    fieldType: "Boolean"
  },
  {
    field: "Contact",
    fieldType: "Relationship"
  }
];

let rows = [
  {
    contact: {
      Name: "Joe",
      Active__c: true,
      Contact: "SomeContact"
    }
  },
  {
    contact: {
      Name: "Rachel",
      Active__c: true
    }
  },
  {
    contact: {
      Name: "Ross",
      Active__c: true
    }
  },
  {
    contact: {
      Name: "Monica",
      Active__c: true
    }
  }
];

let output = {
  data: rows.map(({ contact }) => 
    fields.map(({ field, fieldType: type }) => ({
      field,
      type,
      value: field in contact ? contact[field] : null
    }))
  )
}

document.getElementById('output').appendChild(
  document.createTextNode(JSON.stringify(output, null, 2))
);
<pre id="output"></pre>

Java, A quick and practical guide to combining multiple collections in Java. that is produced by applying the provided mapping function to each element. and then you flatten the Stream before collecting it into a merged list:� To merge or Combine to Lists into a One list. There is one thing that must be true: the type of both list will be equal. For Example : if we have list of string so we can add add another list to the existing list which have list of type string otherwise we can't.


  1. It's not the loops you should worry about, but algorithm's complexity. As I see, you have optional fields in rows, and you didn't ask for null values in desired output. So, I'd propose a solution different from the one of Christos Lytras. Iterating over fields in each row iteration will give you O(N^M) complexity. Where N - is rows.length, and M is fields.length. This is possibly a bad idea. The following code will give you linear complexity O(N+M). Where M is still fields.length and N is a sum of numbers of fields in each row of rows, it sounds even scarier than O(N^M) but, if you have optional fields it will save you a fortune - look for called X times in snippet output.

    // prepare dictionary, later on fields_dict[field] will have O(1) complexity
    const fields_dict = fields.reduce((acc, {field, fieldType}) => {
        acc[field] = fieldType
        return acc
    }, {})
    
    let output2 = {
        data: rows.map(({ contact }) =>
            Object.keys(contact).map(field => ({ // iterate only over existing fields
                field,
                type: fields_dict[field],
                value: contact[field],
            }))
        )
    }
    
  2. And by the way

    I know this can be done using nested for loops but, I'm trying to avoid for loops because of the amount of data I'll have to loop on function

    ...even in modern browsers loops are superior in performance to map(), reduce() and Co., not the other way around.

    Look at the timings in the snippet. At least in my environment for version is twice as fast as map version (on the first run). Of cause, at that moment code is in no way hot by the standards of JIT-compiler, so code haven't been optimized by the browser. After JIT-compilation difference in performance become negligible (press Run code snippet for a couple of times to see). Still, loops are faster, at least on the first run.

    But if you won't test performance of you code, then don't bother microoptimizing it. Better think of algorithm complexity. And, yes, use functional style - it's both easier to write and to read.

    let fields = [
    	{ field: "Name"     , fieldType: "Text" },
    	{ field: "Active__c", fieldType: "Boolean" },
    	{ field: "Contact"  , fieldType: "Relationship" },
    
    	{ field: "extra1"   , fieldType: "something" },
    	{ field: "extra2"   , fieldType: "something" },
    	{ field: "extra3"   , fieldType: "something" },
    	{ field: "extra4"   , fieldType: "something" },
    ];
    
    let rows = [
    	{ contact: { Name: "Joe"   , Active__c: true, Contact: "SomeContact" } },
    	{ contact: { Name: "Rachel", Active__c: true } },
    	{ contact: { Name: "Ross"  , Active__c: true } },
    	{ contact: { Name: "Monica", Active__c: true } },
    
    	{ contact: { Name: "Monica", Active__c: true } },
    	{ contact: { Name: "Monica", Active__c: true } },
    	{ contact: { Name: "Monica", Active__c: true } },
    	{ contact: { Name: "Monica", Active__c: true } },
    	{ contact: { Name: "Monica", Active__c: true } },
    	{ contact: { Name: "Monica", Active__c: true } },
    ];
    
    let i
    
    i = 0
    console.time("Christos Lytras version")
    let output1 = {
    	data: rows.map(({ contact }) => 
    		fields.map(({ field, fieldType: type }) => (i++,{
    			field,
    			type,
    			value: field in contact ? contact[field] : null
    		}))
    	)
    }
    console.timeEnd("Christos Lytras version")
    console.log(`called ${i} times`)
    
    i = 0
    let j = 0
    console.time("functional version")
    const fields_dict = fields.reduce((acc, {field, fieldType}) => { i++, acc[field] = fieldType; return acc }, {})
    let output2 = {
    	data: rows.map(({ contact }) => Object.keys(contact).map(field => (j++,{
    		field,
    		type: fields_dict[field],
    		value: contact[field],
    	})))
    }
    console.timeEnd("functional version")
    console.log(`called ${i+j} times`)
    
    i = 0
    console.time("loop version")
    const fields_dict2 = {}
    for(const {field, fieldType} of fields) { i++; fields_dict2[field] = fieldType }
    const output3 = { data: new Array(rows.length) }
    j = 0
    for(let r = 0 ; r !== rows.length ; ++r ) {
    	const contact = rows[r].contact
    	const contact_another_format = output3.data[r] = []
    	for(const field in contact) {
    		j++
    		contact_another_format.push({
    			field,
    			type: fields_dict2[field],
    			value: contact[field],
    		})
    	}
    }
    console.timeEnd("loop version")
    console.log(`called ${i+j} times`)
    
    // console.log(JSON.stringify(output1, undefined, 2))
    // console.log(JSON.stringify(output2, undefined, 2))
    console.log(JSON.stringify(output3, undefined, 2))
    
    console.log("results are equal:", JSON.stringify(output2) === JSON.stringify(output3)) // intentionally not equal to output1

    10 ways to Join two Lists in Java, Collections class provides several useful static utility methods that operate on collections. One such method is addAll(Collection, T[]) that adds all of the specified� In Python 2, zip returns a list, to avoid creating an unnecessary list, use izip instead (aliased to zip can reduce code changes when you move to Python 3). from itertools import izip as zip So that is still (2.7):


    I have changed a bit of code and removed a conditional check if field exists in contact as javascript will by default return undefined

    let output = {
      data: rows.map(({ contact }) => 
        fields.map(({ field, fieldType: type }) => ({
          field,
          type,
          value: contact[field] // It wills et undefined if field key not present in contact
        }))
      )
    }
    

    Java Program to Join Two Lists, In this program, you'll learn different techniques to join two lists in Java. Example 1: Join Two Lists using addAll() Example 2: Join Two Lists using union(). In this tutorial, we will illustrate how to concatenate multiple collections into one logical collection. We’ll be exploring five different approaches – two using Java 8, one using Guava, one using Apache Commons Collections, and one using only the standard Java 7 SDK.


    Python Join Two Lists, There are several ways to join, or concatenate, two or more lists in Python. One of the easiest ways are by using the + operator. Example. Join two list: list1 =� Let’s discuss a simple yet useful utility of conversion of two lists into a key:value pair dictionary. Method #1 : Naive Method The basic method that can be applied to perform this task is the brute force method to achieve this.


    How to merge two ArrayLists in Java, Using this method, we can combine multiple lists into a single list. Merge arraylists example. import java.util.ArrayList;. import� In Excel, you can combine or merge text from two or more cells, as well as columns and rows,into one cell. If you have a lot of rows of data where you want to combine text, you can simply start typing the combined text in an adjacent column and Excel will fill in the rest for you.


    Method #1 : Using list comprehension + zip() List comprehension does the task of concatenating the similar index elements. The task of zip function is concatenating the resultant string into a single list and return list.