3

I have an log array.

[ '1539024146 17827 add number 1',
  '1539024146 18826 start calculation',
  '1539024146 18826 end calculation',
  '1539024146 18826 14',
  '1539024146 18826 update number 1 1',
  '1539024146 18826 start calculation',
  '1539024146 18826 end calculation,
  '1539024146 18826 4',
  '1539024146 19825 remove number']

I need parser this array to obtain array only with commands. Example:

['add number 1',
'update number 1 1',
'remove number']

My try:

var fs = require('fs');

var array = fs.readFileSync('log.txt').toString().split('\n');

for(var i = 0; i < array.length; i++){
//removing time
array[i] = array[i].replace(/\d{10}[ ]\d{5}/, "");
}
console.log(array);

1 Answer 1

1

One approach might be to iterate your array and then remove any log entries which do not contain a keyword indicating a command. We can use a regex alternation for this:

(add|start|end|update|remove)

Here is a code sample:

var array = [ '1539024146 17827 add number 1',
  '1539024146 18826 start calculation',
  '1539024146 18826 end calculation',
  '1539024146 18826 14',
  '1539024146 18826 update number 1 1',
  '1539024146 18826 start calculation',
  '1539024146 18826 end calculation',
  '1539024146 18826 4',
  '1539024146 19825 remove number'];

var i = array.length;
while (i--) {
    if (!/(add|start|end|update|remove)/.test(array[i])) {
        array.splice(i, 1);
    } 
}

console.log(array);

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

Comments

Your Answer

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