0

In my code, I have used two forEach loops. But in order to optimize my code, I have been told to remove the inner forEach. I have been instructed not to use a forEach loop inside a forEach loop. So I don't want to loop over the second array obj3. I just want to get the values at a certain position. Here is my code : -

var obj2 = [{
  "name": "4134",
  "calls": [

  ]
}]

    var obj3 = [{ Channel: 'SIP/4134-0004462a',
        State: 'Up',
        Accountcode: '7013658596'},
      { Channel: 'SIP/4334-sa',
        State: 'Up',
        Accountcode: '07717754702',
      }]


var function = (obj2, obj3) => {
    obj2.forEach((a) =>
      obj3.forEach((b) => {
        if (b.Channel.includes(a.name)) a.calls = (a.calls || []).concat(Object.assign({}, { MobileNo: b.Accountcode, Status : b.State}));

      })
    );
};

function(obj2, obj3);

The above code loops through obj2 and obj3 and if the value of the name key exist in the Channel key's value then it picks the Accountcode and State from obj3 and pushes them in the calls array of the obj2. Here is the output array:-

    [ {
  "name": "4134",
  "calls": [
    {
      "MobileNo": "7013658596",
      "Status": "Up"
    }
  ]
}]

Any suggestions about how to tackle this?

3
  • 2
    Could you please provide an example of the structures of obj2 and obj3 and also what you'd like the result to look like? Commented Sep 21, 2018 at 5:22
  • 2
    what's the input and the desired output for this function? give example Commented Sep 21, 2018 at 5:22
  • @Phil please check my question Commented Sep 21, 2018 at 7:11

1 Answer 1

2

Try This

var channelArr = [];
const Channels = obj3.reduce((acc, curVal) => {
  obj2.forEach((item)=>{
    if(item.name == curVal.Channel.slice(4,8).toString()){
      item.calls.push({'MobileNo':curVal.Accountcode,'Status': curVal.State})
    }
  })
  return obj2;
}, [])
Sign up to request clarification or add additional context in comments.

3 Comments

I tried your solution but I don't see much difference in the total execution time.
Execution time will vary depending on the amount of data you are testing.
hey this helped me today as the method that I used was giving wrong output sometimes. if(item.name == curVal.Channel.slice(4,8).toString()) this part solved the issue :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.