Solved

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

Posted on 2016-11-10
63 Views
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]]
``````
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
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
• 3
• 3
• 2
• +1

LVL 14

Assisted Solution

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>
<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>
``````
1

LVL 9

Assisted Solution

James Bilous earned 166 total points
ID: 41882383
This question title:
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);
``````
0

LVL 57

Accepted Solution

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>
``````
1

LVL 16

Author Closing Comment

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

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);
``````
0

LVL 9

Expert Comment

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

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 57

Expert Comment

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

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

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

Question has a verified solution.

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

Introduction JSON is an acronym for JavaScript Object Notation.Â  It is a text-string data transport mechanism, capable of representing simple or complex data structures in a consistent and easy-to-read manner.Â  Similar in concept to XML, but more eâ€¦
Boost your ability to deliver ambitious and competitive web apps by choosing the right JavaScript framework to best suit your projectâ€™s needs.
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
Course of the Month8 days, 21 hours left to enroll