3

I have used Node to retrieve a set of results from SQL and they're returned like this;

[
   {
   "event_id": 111111,
   "date_time": "2012-11-16T01:59:07.000Z",
   "agent_addr": "127.0.0.1",
   "priority": 6,
   "message": "aaaaaaaaa",
   "up_time": 9015040,
   "hostname": "bbbbbbb",
   "context": "ccccccc"
},
   {
   "event_id": 111112,
   "date_time": "2012-11-16T01:59:07.000Z",
   "agent_addr": "127.0.0.1",
   "priority": 6,
   "message": "aaaaaaaaa",
   "up_time": 9015040,
   "hostname": "bbbbbbb",
   "context": "ddddddd"
},
]

There are usually a lot of entries in the array and I need to efficiently filter the array to show only the entries that have a context of "ccccccc". I've tried a for loop, but it's incredibly slow.

Any suggesstions?

1
  • 5
    Why can't you constrain your query to only return cccccccc contexts? Commented Feb 4, 2013 at 10:38

3 Answers 3

9

There is a very simple way of doing that if you want to do that in node and don't want to use sql for that you can user javascript built-in Array.filter function.

var output = arr.filter(function(x){return x.context=="ccccccc"}); //arr here is you result array

The ouput array will contains only objects having context "ccccccc".

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

Comments

2

Another way of doing what Khurrum said, is with the arrow function. It has the same result but some people prefer that notation.

var output = arr.filter(x => x.context == "ccccccc" );

Comments

0
  1. As suggested by Matt, why not include WHERE context = "ccccccc" in yout SQL query?

  2. Else if you must keep all in maybe use one of the following to filter the results

    // Place all "ccccccc" context row in an array
    
    var ccccccc = [];
    
    for (var i = results.length - 1; i >= 0; i--) {
      if(results[i] == 'ccccccc')
        ccccccc.push(results[i]);
    };
    
    // Place any context in an named array within an object
    
    var contexts = {};
    for (var i = results.length - 1; i >= 0; i--) {
    
      if(contexts[results[i]] == 'undefined')
        contexts[results[i]]
    
        contexts[results[i]].push(results[i]);
    };
    

    or use the underscore (or similar) filter function.

1 Comment

There is native V8 Array.filter (I believe underscore will use that anyway).

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.