473,761 Members | 3,651 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Sorting array against other array

Say I have two arrays with the same number of elements that are related:

var a1 = [1,3,2];
var b2 = ["a","b","c"];

I need to sort a1 but have the order of the elements in b2 reflect the
any new order in a1. So if a1 sorts as

[1,2,3] then b2 becomes
["a","c","b"]

or if a1 sorts as

[3,2,1] then b2 becomes
["b","c","a"]

Andrew Poulos
Jan 17 '07 #1
4 3491
Lee
Andrew Poulos said:
>
Say I have two arrays with the same number of elements that are related:

var a1 = [1,3,2];
var b2 = ["a","b","c"];

I need to sort a1 but have the order of the elements in b2 reflect the
any new order in a1. So if a1 sorts as

[1,2,3] then b2 becomes
["a","c","b"]

or if a1 sorts as

[3,2,1] then b2 becomes
["b","c","a"]
If possible, combine your two arrays into an array of objects that each have two
fields, then define a custom sort function that compares only the fields that
you want to sort by. This example assumes that the sort key is numeric:

<html>
<body>
<script type="text/javascript">

var pair = [ {key:1, info:"a"},
{key:3, info:"b"},
{key:2, info:"c"}
];

function comparePair(a,b ) {
return a.key-b.key;
}

pair.sort(compa rePair);
for (var i=0;i<pair.leng th;i++) {
document.write( pair[i].info,"<br>");
}
</script>
</body>
</html>
--

Jan 17 '07 #2
Andrew Poulos wrote:
Say I have two arrays with the same number of elements that are
related: var a1 = [1,3,2];
var b2 = ["a","b","c"];
I need to sort a1 but have the order of the elements in b2 reflect the
any new order in a1. So if a1 sorts as
I haven't done extensive testing, but I threw this together:

var a1 = [1,3,2,5,4];
var a2 = ["a","b","c","d" ,"e"];
var a3 = ["z","y","x","w" ,"v"];

Array.prototype .multisort = function() {
var sortArray = [];
for (var i=0; i<this.length; i++) {
sortArray[i] = [this[i]];
for (var j=0; j<arguments.len gth; j++) {
if (arguments[j].length!=this.l ength) { return false; }
sortArray[i][j+1] = arguments[j][i];
}
}
sortArray.sort( );
for (var i=0; i<sortArray.len gth; i++) {
this[i] = sortArray[i][0];
for (var j=0; j<arguments.len gth; j++) {
arguments[j][i] = sortArray[i][j+1];
}
}
return true;
}

alert(a1+"\n"+a 2+"\n"+a3);
a1.multisort(a2 ,a3);
alert(a1+"\n"+a 2+"\n"+a3);
a2.multisort(a1 ,a3);
alert(a1+"\n"+a 2+"\n"+a3);
a3.multisort(a1 ,a2);
alert(a1+"\n"+a 2+"\n"+a3);
Let me know if it works for you.

--
Matt Kruse
http://www.JavascriptToolbox.com
http://www.AjaxToolbox.com
Jan 17 '07 #3
In comp.lang.javas cript message <45ad7ae6$0$279 31$5a62ac22@per-
qv1-newsreader-01.iinet.net.au >, Wed, 17 Jan 2007 12:24:55, Andrew
Poulos <ap*****@hotmai l.composted:
>
I need to sort a1 but have the order of the elements in b2 reflect the
any new order in a1.
You could replace the content of each element of A1 with an Object
containing the previous content and also the corresponding element of
B1; then sort; then regenerate B1.

If you have lots of subsidiaries, say b00 to b99, you could extend that.
Or you could add as above to each element of A1 its index; sort; extract
the sorted indexes and use them to rearrange every bxx. I doubt
whether, in Javascript, that would be better.

If you have editable sorting code, you can just modify it so where it
swaps a1 it also swaps b2. But that should be less efficient.

--
(c) John Stockton, Surrey, UK. ?@merlyn.demon. co.uk Turnpike v6.05 IE 6
news:comp.lang. javascript FAQ <URL:http://www.jibbering.c om/faq/index.html>.
<URL:http://www.merlyn.demo n.co.uk/js-index.htmjscr maths, dates, sources.
<URL:http://www.merlyn.demo n.co.uk/TP/BP/Delphi/jscr/&c, FAQ items, links.
Jan 18 '07 #4
Matt Kruse wrote:
Andrew Poulos wrote:
>Say I have two arrays with the same number of elements that are
related: var a1 = [1,3,2];
var b2 = ["a","b","c"];
I need to sort a1 but have the order of the elements in b2 reflect the
any new order in a1. So if a1 sorts as

I haven't done extensive testing, but I threw this together:

var a1 = [1,3,2,5,4];
var a2 = ["a","b","c","d" ,"e"];
var a3 = ["z","y","x","w" ,"v"];

Array.prototype .multisort = function() {
var sortArray = [];
for (var i=0; i<this.length; i++) {
sortArray[i] = [this[i]];
for (var j=0; j<arguments.len gth; j++) {
if (arguments[j].length!=this.l ength) { return false; }
sortArray[i][j+1] = arguments[j][i];
}
}
sortArray.sort( );
for (var i=0; i<sortArray.len gth; i++) {
this[i] = sortArray[i][0];
for (var j=0; j<arguments.len gth; j++) {
arguments[j][i] = sortArray[i][j+1];
}
}
return true;
}

alert(a1+"\n"+a 2+"\n"+a3);
a1.multisort(a2 ,a3);
alert(a1+"\n"+a 2+"\n"+a3);
a2.multisort(a1 ,a3);
alert(a1+"\n"+a 2+"\n"+a3);
a3.multisort(a1 ,a2);
alert(a1+"\n"+a 2+"\n"+a3);
Let me know if it works for you.
Sorry, my example used numerals but the stuff I'm working on also uses
strings.

Thanks, what you did works fine - it correctly puts "Test" before
"apple". Except I need it to sort, where strings, alphabetically and not
based on ASCII value. The case of the elements of the arrays is not
supposed to change so should I copy the "base" array; convert each
element's case to lower case, and then do the sort using it?

Andrew Poulos
Jan 23 '07 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
3266
by: Federico G. Babelis | last post by:
Hi All: I have this line of code, but the syntax check in VB.NET 2003 and also in VB.NET 2005 Beta 2 shows as unknown: Dim local4 As Byte Fixed(local4 = AddressOf dest(offset)) CType(local4, Short) = CType(src, Short)
0
3240
by: Brian Henry | last post by:
Here is another virtual mode example for the .NET 2.0 framework while working with the list view. Since you can not access the items collection of the list view you need to do sorting another way... here is my code on how I did it to help anyone starting out get an idea of how to use virtual mode in ..NET 2.0 Imports CrystalDecisions.CrystalReports.Engine Imports CrystalDecisions.Shared
25
11386
by: Allie | last post by:
How would I go about sorting this structure by title? typedef struct { char author; char title; char code; int hold; int loan; } LIBRARY;
11
2190
by: Registered User | last post by:
What is the name of the following sorting method? for (i=0; i<n-1; i++) for (j=i+1; j<n; j++) if (a>a) swap(&a, &a); It seems to be the opposite of bubble sort, with lighter elements going in their proper positions first. However, this one does not compare a with a, as the normal bubble sort does.
7
4827
by: Kamal | last post by:
Hello all, I have a very simple html table with collapsible rows and sorting capabilities. The collapsible row is hidden with css rule (display:none). When one clicks in the left of the expandable row, the hidden row is made visible with css. The problem is when i sort the rows, the hidden rows get sorted as well which i don't want and want to be moved (while sorting) relative to their parent rows. The following is my complete html code...
1
7189
KevinADC
by: KevinADC | last post by:
Introduction In part one we discussed the default sort function. In part two we will discuss more advanced techniques you can use to sort data. Some of the techniques might introduce unfamiliar methods or syntax to a less experienced perl coder. I will post links to online resources you can read if necessary. Experienced perl coders might find nothing new or useful contained in this article. Short Review In part one I showed you some...
5
3186
by: lemlimlee | last post by:
hello, this is the task i need to do: For this task, you are to develop a Java program that allows a user to search or sort an array of numbers using an algorithm that the user chooses. The search algorithms that can be used are Linear Search and Binary Search. The sorting algorithms are bubble, selection and Insertion sort. First, the user is asked whether he/she wants to perform a search option, a sort operation, or exit the program. If...
1
2424
by: arnuld | last post by:
On Mon, 29 Sep 2008 15:16:56 +0100, Ben Bacarisse wrote: An abstract overview of my own program by Ben had helped me focus on the design issue first. I came to know that whole problem went into the wrong direction as compared to what was intended. I think I am working on this program from last 1 month and it is still not done, Here is the intent:
5
4955
by: jrod11 | last post by:
hi, I found a jquery html table sorting code i have implemented. I am trying to figure out how to edit how many colums there are, but every time i remove code that I think controls how many colums there are, it crashes. There are currently 6 columns, and I only want 4. How do I remove the last two (discount and date)? Here is a link: http://www.jaredmoore.com/tablesorter/docs/salestable.html Here is some jquery js that I think...
0
9522
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10111
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9765
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7327
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6603
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5215
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5364
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3866
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2738
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.