arnoldssss
arnoldssss

Reputation: 488

Execute a function for some conditions for values in array js

I want to execute a function for all "on" rows with same userId from this array:

productIds, userIds, status
[ 'com--test,LFutx9mQbTTyRo4A9Re5ksjdnfsI4cKN4q2,on',
  'com--test,LFutx9mQbTTyRo4A9Re5ksjdnfsI4cKN4q2,off',
  'com--fxtrimester,LFutx9mQbTTyRoldksfns4A9Re5I4cKN4q2,on',
  'com--fxyear,LFutx9mQbTTyRoldksfns4A9Re5I4cKN4q2,on'
  'com--fxtrimester,LFutx9mQbTTyRoldksfns4A9Re5I4cKN4q2,off',
  'com--fxyear,LFutx9mQbTTyRoldksfns4A9Re5I4cKN4q2,off',
  'com--fxyear,SEzlksdfMpW3FxkSbzL7eo5MmqkPczCl2,on',
  'com--fxtrimester,SEzlksdfMpW3FxkSbzL7eo5MmqkPczCl2,on' ]

So for this

  'com--fxtrimester,SEzlksdfMpW3FxkSbzL7eo5MmqkPczCl2,on',
  'com--fxyear,SEzlksdfMpW3FxkSbzL7eo5MmqkPczCl2,on',

or this:

'com--fxtrimester,LFutx9mQbTTyRoldksfns4A9Re5I4cKN4q2,on',
  'com--fxyear,LFutx9mQbTTyRoldksfns4A9Re5I4cKN4q2,on'

Execute something like:

`setProductsToUser(productIds,userId)`
-- First parameter is array ([com--fxtrimester, com--fxyear]) and the second is a userId (string) (SEzlksdfMpW3FxkSbzL7eo5MmqkPczCl2)

any idea? I try to split the object into three objects and iterate for every key but it is so mucho code and the iteration for each userId is not working. The second for loop compares the same values even when I am selecting a different key for the array. Edit: also I need to send just one request per userId

Why the for loops are not workinggg!!

       var finals= 0
   //the array of the question is this "unique" and what it does is delete the duplicated values just here
   var unique = products.filter(function(elem, index, self) {
    return index == self.indexOf(elem);
  })
   console.log(unique)
   unique.forEach(function(data) {
//spliting the array and when it finish iterate the arrays
    finals++
    var dataArray = data.split(',');
    productIds.push(dataArray[0]);
    userIds.push(dataArray[1]);
    status.push(dataArray[2]);
    if(finals == unique.length) {
      console.log("userIDs "+userIds.length)  
      for (var h = 0; h <= userIds.length ; h++) {
        if( status[h] == "on") {

          for (var k = 0; k <= userIds.length  ; k++) {
            if(status[k] === "on" && userIds[k] == userIds[h]  && productIds[h] == productIds[k] ) {
              productsOn.push(productIds[k]);
              userId = userIds[h];
            }
          }    
        //setProductsToUser(productsOn,userId) 
      }
    }


  }

}); 

Upvotes: 0

Views: 51

Answers (2)

Andrew Wynham
Andrew Wynham

Reputation: 2398

Here is what I think you are looking for. Note that you just want to get really used to .map, .filter, and .reduce with JavaScript Arrays to save yourself lines of code. This is done in multiple steps so its clear whats being done but could be shortened even further. I'll add a concise version too but be sure you understand whats going on if you are going to use.

var input = [ 'com--test,LFutx9mQbTTyRo4A9Re5ksjdnfsI4cKN4q2,on',
  'com--test,LFutx9mQbTTyRo4A9Re5ksjdnfsI4cKN4q2,off',
  'com--fxtrimester,LFutx9mQbTTyRoldksfns4A9Re5I4cKN4q2,on',
  'com--fxyear,LFutx9mQbTTyRoldksfns4A9Re5I4cKN4q2,on',
  'com--fxtrimester,LFutx9mQbTTyRoldksfns4A9Re5I4cKN4q2,off',
  'com--fxyear,LFutx9mQbTTyRoldksfns4A9Re5I4cKN4q2,off',
  'com--fxyear,SEzlksdfMpW3FxkSbzL7eo5MmqkPczCl2,on',
  'com--fxtrimester,SEzlksdfMpW3FxkSbzL7eo5MmqkPczCl2,on' ];

var objects = input.map(function(row) {
  var split = row.split(',');
  return {
    productId: split[0],
    userId: split[1],
    status: split[2]
  };
});

var filtered = objects.filter(function(obj) {
  return obj.status === 'on';
});

var userProductsMap = filtered.reduce(function(map, val) {
  var productIds = map[val.userId];
  if (!productIds) {
    productIds = [];
    map[val.userId] = productIds;
  }
  productIds.push(val.productId);
  return map;
}, {});

for (var userId in userProductsMap) {
    var productIds = userProductsMap[userId];
    console.log('setProductstoUsers(' + userId + ', ' + productIds + ')');
}

And here is a concise version as promised:

var userProductsMap2 = input.reduce(function(map, val) {
    var split = val.split(',');
    var productId = split[0];
    var userId = split[1];
    var status = split[2];
    if (status !== 'on') {
        return map;
    }
    map[userId] = map[userId] || [];    
    map[userId].push(productId);
    return map;
}, {});

for (var userId in userProductsMap2) {
    var productIds = userProductsMap2[userId];
    console.log('setProductstoUsers(' + userId + ', [' + productIds + '])');
}

Upvotes: 0

Andrew Shepherd
Andrew Shepherd

Reputation: 45262

This kind of problem is easily solved with regular expressions.

Here's an example:

var input = [ 'com--test,LFutx9mQbTTyRo4A9Re5ksjdnfsI4cKN4q2,on',
  'com--test,LFutx9mQbTTyRo4A9Re5ksjdnfsI4cKN4q2,off',
  'com--fxtrimester,LFutx9mQbTTyRoldksfns4A9Re5I4cKN4q2,on',
  'com--fxyear,LFutx9mQbTTyRoldksfns4A9Re5I4cKN4q2,on',
  'com--fxtrimester,LFutx9mQbTTyRoldksfns4A9Re5I4cKN4q2,off',
  'com--fxyear,LFutx9mQbTTyRoldksfns4A9Re5I4cKN4q2,off',
  'com--fxyear,SEzlksdfMpW3FxkSbzL7eo5MmqkPczCl2,on',
  'com--fxtrimester,SEzlksdfMpW3FxkSbzL7eo5MmqkPczCl2,on' ];

  var r = /(com--\w+),(\w+),(\w+)/;

  var parsedValues = input.map(function(s) {
    var match = r.exec(s);
    return {
        productId: match[1],
      userId: match[2],
      onOrOff: match[3]
    };
  });

  for(var i = 0; i < parsedValues.length; ++i) {
    var c = parsedValues[i];
    if(c.onOrOff === 'on') {
        console.log("setProductstoUsers('" + c.productId + "', '" + c.userId + "')");
    }
  }

The output will be as follows:

setProductstoUsers('com--test', 'LFutx9mQbTTyRo4A9Re5ksjdnfsI4cKN4q2')
setProductstoUsers('com--fxtrimester', 'LFutx9mQbTTyRoldksfns4A9Re5I4cKN4q2')
setProductstoUsers('com--fxyear', 'LFutx9mQbTTyRoldksfns4A9Re5I4cKN4q2')
setProductstoUsers('com--fxyear', 'SEzlksdfMpW3FxkSbzL7eo5MmqkPczCl2')
setProductstoUsers('com--fxtrimester', 'SEzlksdfMpW3FxkSbzL7eo5MmqkPczCl2')

Upvotes: 1

Related Questions