Compare Arrays with Javascript and build another Array

48 views Asked by At

In Javascript: I have an existing array like [4,5,6,10] - (These are 'repid').

I have an ajax response like [{"repid":5,"avgAmount":2.5},{"salesrepid":10,"avgAmount":3.0}].

I have to build a third array which will compare the 'repids' of the 2 arrays and build a third array so that it will place a '0' if the repids do not match or else the 'avgAmount' if they match.

So, in my case above, I would 'build' a third array: [0, 2.5, 0, 3.0]

I've tried many variances of:

//need to assign the sales average values to the proper repid
for (var i = 0; i < repIds.length; i++) {
   for (var j = 0; j < salesrepids.length; j++) {
         if (repIds[i] == salesrepids[j]) {
              salesvalues.push(key.avgAmount);
              } else { salesvalues.push("0"); }
               };
          }
      }
   }
3

There are 3 answers

1
Danmoreng On BEST ANSWER

You need to address the correct keys of your objects. And also only add the 0 in case you don't find any matching entry:

var repIds = [4, 5, 6, 10];
var salesrepids = [{"repid": 5, "avgAmount": 2.5}, {"repid": 10, "avgAmount": 3.0}]
var salesvalues = [];
for (var i = 0; i < repIds.length; i++) {
    var noMatch = true;
    for (var j = 0; j < salesrepids.length; j++) {
        if (repIds[i] === salesrepids[j]['repid']) {
            salesvalues.push(salesrepids[j]['avgAmount']);
            noMatch = false;
        }
    }
    if (noMatch) {
        salesvalues.push(0);
    }
}
console.log(salesvalues);

1
mscdeveloper On

May be like this:

  var repids  = [4,5,6,10];
  var returns = [{"repid":5,"avgAmount":2.5},{"salesrepid":10,"avgAmount":3.0}];
  var results = [];
  
  for(var key in returns){
     if(repids.includes(returns[key].repid)){
       results.push(returns[key].repid);
       results.push(returns[key].avgAmount);
     }
     if(repids.includes(returns[key].salesrepid)){
       results.push(returns[key].salesrepid);
       results.push(returns[key].avgAmount);
     }
  }
  console.log(results);

1
adiga On

You can do something like using map and find:

Loop through the first array -> Check if the id exists in the second array using find -> If yes, return it's avgAmount else return 0.

const ids = [4,5,6,10],
   amounts = [{"repid":5,"avgAmount":2.5},{"repid":10,"avgAmount":3.0}];

const output = ids.map(i => {
  const found = amounts.find(a => a.repid === i);
  return found ? found.avgAmount : 0;
})

console.log(output)