[2 days left] What’s wrong with your cloud strategy? Learn why multicloud solutions matter with Nimble Storage.Register Now

x
?
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
Medium Priority
?
73 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 3
  • 2
  • +1
10 Comments
 
LVL 14

Assisted Solution

by:Pierre Cornelius
Pierre Cornelius earned 672 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 9

Assisted Solution

by:James Bilous
James Bilous earned 664 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 59

Accepted Solution

by:
Julian Hansen earned 664 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
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 
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 9

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 59

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

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!

Question has a verified solution.

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

Introduction Chart.js, used properly, can visually add a difference to your charting applications. It engages your visitors and allows them to interact with data they otherwise wouldn't be able to without expensive and complicated systems. For this…
Introduction If you're like most people, you have occasionally made a typographical error when you're entering information into an online form.  And to your consternation, the browser remembers the error, and offers to autocomplete your future entr…
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn the basics of jQuery, including how to invoke it on a web page. 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.: (CODE)
Suggested Courses

656 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