Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript conditions in an object

I'm pretty new in js, I have an array that looks like this:

[ 'com--test,LFutx9mQbTTyRo4A9Re5ksjdnfsI4cKN4q2,on',
  'com--test,LFutx9mQbTTyRo4A9Re5ksjdnfsI4cKN4q2,off',
  'com--fxtrimester,SEzlksdfMpW3FxkSbzL7eo5MmqkPczCl2,on',
  'com--fxtrimester,LFutx9mQbTTyRoldksfns4A9Re5I4cKN4q2,on'
  'com--fxtrimester,LFutx9mQbTTyRoldksfns4A9Re5I4cKN4q2,off',
  'com--fxyear,SEzlksdfMpW3FxkSbzL7eo5MmqkPczCl2,on',
  'com--fxyear,SEzlksdfMpksfhksfMmqkPczCl2,off' ]

How can I delete the rows from the array that has: -> the last value "off" AND the first two values the same as a line with the "on" value
like this:

   (*) [ 'com--test,LFutx9mQbTTyRo4A9Re5ksjdnfsI4cKN4q2,on',
      'com--fxtrimester,SEzlksdfMpW3FxkSbzL7eo5MmqkPczCl2,on',
      'com--fxtrimester,LFutx9mQbTTyRoldksfns4A9Re5I4cKN4q2,on',
      'com--fxyear,SEzlksdfMpW3FxkSbzL7eo5MmqkPczCl2,on',
      'com--fxyear,SEzlksdfMpksfhksfMmqkPczCl2,off' ]

So I was like:

var productIds = [];
var userIds = [];
var status = [];
unique.forEach(function(data) {
  var dataArray = data.split(',');
  productIds.push(dataArray[0]);
  userIds.push(dataArray[1]);
  status.push(dataArray[2]);
});

for (var h = 0; userIds.length >= h; h++) {
  if (status[h] == "on") {
    for (var k = 0; userIds.length >= k; k++) {
      if (status[k] == "off" && 
          userIds[h] == userIds[k] && 
          productIds[h] == productIds[k]) {
        delete status[k];
        delete userIds[k];  
        delete productIds[k];
      }
    }    
  }
} 

But I think it is so much code... and well, just the forEach is the one working fine (separating into three objects) And the for loops I think work wrong because forEach is async. So is there any way I could improve the code to get that output mentioned (*)?

After this I need to send the array with the off rows that were left.

like image 984
arnoldssss Avatar asked Mar 17 '26 23:03

arnoldssss


1 Answers

You can use Array filter.

Here an example:

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

function checkFilter(str) {
   return str.indexOf('off') !== str.length - 3 || str.indexOf('co') !== 0;
}

function myFunction() {
   document.getElementById("demo").innerHTML =  array.filter(checkFilter);
}

You can test this code here http://www.w3schools.com/code/tryit.asp?filename=FBN71QBHVUS1

The doc http://www.w3schools.com/jsref/jsref_filter.asp

like image 119
fingerprints Avatar answered Mar 20 '26 13:03

fingerprints



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!