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
52 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
ID: 41882355
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 8

Assisted Solution

by:James Bilous
James Bilous earned 166 total points
ID: 41882383
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 54

Accepted Solution

by:
Julian Hansen earned 166 total points
ID: 41882391
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
Master Your Team's Linux and Cloud Stack

Come see why top tech companies like Mailchimp and Media Temple use Linux Academy to build their employee training programs.

 
LVL 16

Author Closing Comment

by:SSupreme
ID: 41882491
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
ID: 41882498
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
 
LVL 8

Expert Comment

by:James Bilous
ID: 41882501
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
ID: 41883379
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 54

Expert Comment

by:Julian Hansen
ID: 41883402
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
ID: 41883419
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
ID: 41885471
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

Live: Real-Time Solutions, Start Here

Receive instant 1:1 support from technology experts, using our real-time conversation and whiteboard interface. Your first 5 minutes are always free.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

There are a couple ways to attach a JavaScript function to dynamically created elements. You can make a new script for each element as it’s created or you can use delegation. Delegation allows a single script that is added at page creation to mat…
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 …
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…

785 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