Solved

How to get array of arrays from array of arrays based on value of first or second element

Posted on 2016-11-10
10
36 Views
Last Modified: 2016-11-13
What would be the most efficient way to get specific arrays from array base on index and value.
Example of array:
var oldarray= [[11,28],[11,29],[11,30],[11,34],[63,26],[63,27],[63,28],[63,29],[63,30],[63,34]]

Open in new window

If index 0 and value 11, output [[11,28],[11,29],[11,30],[11,34]]
If index 1 and value 28, output [[11,28],[63,28]]
Which pre built function should be used in such case?
0
Comment
Question by:SSupreme
  • 3
  • 3
  • 2
  • +1
10 Comments
 
LVL 14

Assisted Solution

by:Pierre Cornelius
Pierre Cornelius earned 168 total points
Comment Utility
To my knowledge there is no such native function, you need to search the array. I have put together an example for you:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
	<div id="notes"></div>
	<script>
		var oldarray= [[11,28],[11,29],[11,30],[11,34],[63,26],[63,27],[63,28],[63,29],[63,30],[63,34]]
		function search_array(input_array, index, value)
		{
			var i,j, ret=[];
			
			for (i=0; i<input_array.length; i++)
			{
				if (input_array[i][index] == value) ret.push(input_array[i]);
			}
			return ret;
		}
		
		function format2D(a) {
			var str="[";
			for (var i = 0; i<a.length; i++) {
				str+="["+a[i].toString()+"],";
			}
			str=str.substr(0,str.length-1);
			str+="]";
			return str;
		}

		var a = search_array(oldarray,1,28), b = search_array(oldarray,0,11);
		var n = document.getElementById('notes');
		n.innerHTML = format2D(a) + "<br>" + format2D(b);
		
	</script>
</body>
</html>

Open in new window

1
 
LVL 7

Assisted Solution

by:James Bilous
James Bilous earned 166 total points
Comment Utility
This question title: tim-and-eric-mind-blown.gif
But seriously, you can easily do this with a filter:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

Something like:

var index = 1;
var value = 11;
var oldarray= [[11,28],[11,29],[11,30],[11,34],[63,26],[63,27],[63,28],[63,29],[63,30],[63,34]];

function myFilter(item) {
   return item[index] === value;
}

var filtered = oldarray.filter(myFilter);

Open in new window

0
 
LVL 51

Accepted Solution

by:
Julian Hansen earned 166 total points
Comment Utility
Just use a loop
<script>
var oldarray= [[11,28],[11,29],[11,30],[11,34],[63,26],[63,27],[63,28],[63,29],[63,30],[63,34]];
var index = 0;
var value=11;
var result = [];
for (var i=0; i < oldarray.length;i++) {
    if (oldarray[i][index] == value)
		result.push(oldarray[i]);
}
console.log(result);
</script>

Open in new window

1
 
LVL 16

Author Closing Comment

by:SSupreme
Comment Utility
It was difficult, I was surprised that Julian's was the best performing solution, but it is the same technique as Pierre's one, Pierre's is only 10% slower after simplification. I wanted something like James provided but it's 40% slower! I thought that build in filter() or map() is better. Please share you thoughts about built in functions in general.
0
 
LVL 16

Author Comment

by:SSupreme
Comment Utility
Pierre's simplified
	
var oldarray= [[11,28],[11,29],[11,30],[11,34],[63,26],[63,27],[63,28],[63,29],[63,30],[63,34]]
		function search_array(input_array, index, value)
		{
			var i,j, ret=[];
			
			for (i=0; i<input_array.length; i++)
			{
				if (input_array[i][index] == value) ret.push(input_array[i]);
			}
			return ret;
		}
		
		var a = search_array(oldarray,0,63)
		var n = document.getElementById('notes1');
   n.innerHTML = JSON.stringify(a);

Open in new window

0
What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

 
LVL 7

Expert Comment

by:James Bilous
Comment Utility
JS's native filter() is known to be slow because it is robust and handles multiple edge cases that you won't run into in most practical uses.

http://www.monkeyandcrow.com/blog/why_javascripts_filter_is_slow/
1
 
LVL 14

Expert Comment

by:Pierre Cornelius
Comment Utility
I don't agree with your statement about my code being slower. How can it be when he simply copied mine almost verbatim? The functional part of my example and his has zero difference. It searches the array for the values requested.

When comparing performance you should compare apples with apples, not apples with the apple tree. Comparing a function that does what you required and offers a way of using that code on different arrays with different values is not the same as simply calling it once in your main code in the form of a loop using global variables. Obviously calling a function adds some performance overhead.

Clearly using some sort of a function is more suitable for your needs (and in fact what you asked for) else why not merely define those arrays (e.g. arr1 =  [[11,28],[11,29],[11,30],[11,34]], arr2=[[11,28],[63,28]];) instead of searching for them from a main array in the script?

Another note on performance:
I'm not sure on your intended use but if you're just going to search the array a few times then doing it in a loop directly will be better. If you're going to search it many times, then using the function would be better. I ran some tests to illustrate this:
repeat 10 times:
Function: 0.485ms
Loop only: 0.060ms

repeat 1000 times:
Function: 0.735ms
Loop only: 1.340ms
0
 
LVL 51

Expert Comment

by:Julian Hansen
Comment Utility
How can it be when he simply copied mine almost verbatim?
Correction - I did not copy your code, Pierre, when I got to this question there were no comments. I entered my post, hit submit and left for a meeting. Thanks to Telkom my line went down and the post did not go through - I submitted again when I got back and it appeared after yours.

Yes, it is substantially the same as yours and performance between the two is negligible - however please don't make statements about copying before clarifying the situation.

If you are unhappy with the allocation of points post back and I will open the question for a regrade.
0
 
LVL 14

Expert Comment

by:Pierre Cornelius
Comment Utility
ok Julian, that makes sense. I just saw an hour passed between our answers and assumed you copied mine. Apologies for thinking the worst. I have had experts do that in the past just to try and muscle in on points and it is rather annoying. No need to re-open the question. I don't care too much about the points. My focus here on EE is mainly to help others whilst learning new things myself.

P.S. I'm a saffa too :) Gotta love Telkom, right?!
2
 
LVL 16

Author Comment

by:SSupreme
Comment Utility
https://jsfiddle.net/s6uomhs2/ I created this fiddle, added while loop and do/while. From mine observation in single loop while and do/while have better performance, but in multi loop function is a little faster. In Chrome and Firefox results are vary.
0

Featured Post

Top 6 Sources for Identifying Threat Actor TTPs

Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

Join & Write a Comment

Suggested Solutions

Introduction Knockoutjs (Knockout) is a JavaScript framework (Model View ViewModel or MVVM framework).   The main ideology behind Knockout is to control from JavaScript how a page looks whilst creating an engaging user experience in the least …
I found this questions asking how to do this in many different forums, so I will describe here how to implement a solution using PHP and AJAX. The logical flow for the problem should be: Write an event handler for the first drop down box to get …
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

743 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

8 Experts available now in Live!

Get 1:1 Help Now