Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 75
  • Last Modified:

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

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
SSupreme
Asked:
SSupreme
  • 3
  • 3
  • 2
  • +1
3 Solutions
 
Pierre CorneliusCommented:
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
 
James BilousSoftware EngineerCommented:
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
 
Julian HansenCommented:
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
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
SSupremeAuthor Commented:
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
 
SSupremeAuthor Commented:
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
 
James BilousSoftware EngineerCommented:
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
 
Pierre CorneliusCommented:
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
 
Julian HansenCommented:
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
 
Pierre CorneliusCommented:
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
 
SSupremeAuthor Commented:
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

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 3
  • 3
  • 2
  • +1
Tackle projects and never again get stuck behind a technical roadblock.
Join Now