0

There are two arrays I have created in my modules. That has been inserted below.

var a = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];
var b = [{name:"Fri", value:10}, {name:"Thu", value:5}];

My requirement is I want to create another array with order of array "a". If the name is not contain in "b" array, I need to push value 0 into an new array.

Expected result,

var result = [0, 0, 0, 5, 10, 0, 0];

My Code,

const result= [];
    _.map(a, (el, i) => {
      if(b[i] !== undefined) {
        if(el === b[i].name) {
          result.push(b[i].value);
        } else {
          result.push(0);
        }
      }
    });
1
  • @MattThurston, I have updated the code. But the output still I'm getting wrong one. Commented Jan 25, 2018 at 2:06

2 Answers 2

2

Array#find() is helpful here

var a = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];
var b = [{name:"Fri", value:10}, {name:"Thu", value:5}];

var res = a.map(s => {
  var bMatch = b.find(o => o.name === s);// returns found object or undefined
  return bMatch ? bMatch.value : 0;
});

console.log(JSON.stringify(res))

Sign up to request clarification or add additional context in comments.

Comments

1

You need to look up the value inside of b by iterating through all elements of b, in order to know if it exists.

I would recommend adjusting the structure of b to look like:

var b = {
  "Fri": 10,
  "Thu": 5,
}

If that's not an option, then here's how you could do it with your current structure:

var a = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];
var b = [{name:"Fri", value:10}, {name:"Thu", value:5}];

const result = a.map((aVal) => {
    var found = 0; // default to 0 if not found
    // edit: this iteration could be replaced with find in the other answer
    b.forEach((bVal) => { // try to find the day in b
       if (bVal.name === aVal) { // if the day is found 
          found = bVal.value; // set the found value to value field of b element
       }
    });
    return found;
 });

 console.log(result);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.