JoeBe
JoeBe

Reputation: 1290

How to create an object based on filtering two arrays with a filter criteria from one array in Javascript/ES6?

Let's assume I have two arrays of the same length:

const arr_one = [1,2,null,4,null,6];
const arr_two = ["a","b","c","d","e","f"];

Now I would like to create one object called arr_final out of it that uses the values of arr_two as keys and the values of arr_one as values for arr_final, but only for values in arr_one that are not null.

So the desired outcome would be:

const obj_final = {"a": 1, "b": 2, "d": 4, "f": 6}

Current solution

Currently, I am having a for loop with an if check inside it and would like to change it to a more shorter code:

let arr_final = {};
for (const [i, v] of arr_one.entries()) {
    if (v != null) {
        arr_final[arr_two[i]] = v
    }
};

How can I achieve this with a minimal number of code lines?

Upvotes: 1

Views: 57

Answers (3)

Sudhir
Sudhir

Reputation: 125

Use lodash zipObject utility Here is a reference: https://lodash.com/docs/4.17.15#zipObject

Upvotes: 0

onecompileman
onecompileman

Reputation: 940

Here's the shortest one-liner approach, that requires 1 array iteration only

const arr_one = [1,2,null,4,null,6];
const arr_two = ["a","b","c","d","e","f"];

const fa = arr_one.reduce((a, e, i) => e ? { ...a, [arr_two[i]]: e } : a ,{});
console.log(fa);

Upvotes: 1

kapil pandey
kapil pandey

Reputation: 1903

Your code looks optimal, here is an another version to your solution:

const arr_one = [1,2,null,4,null,6];
const arr_two = ["a","b","c","d","e","f"];

let arr_final={}
arr_one.map((itm,indx)=>{
  if(itm!==null){
    arr_final[arr_two[indx]]=itm
  }
})
    console.log(arr_final)

Upvotes: 0

Related Questions