Getting Unique value from an array - javascript

So I have 2 arrays like these ...
var browser_names = ["Firefox", "Maxthon", "Opera", "Opera", "Chrome", "Chrome", "Edge", "Firefox"]
var user_count = [3, 3, 3, 3, 7, 20, 94, 142]
I want results like these
var result_browser_names = ["Firefox", "Maxthon", "Opera", "Chrome", "Edge"]
var result_user_count = [145, 3, 6, 27, 94]
As you can see 'result_browser_names' contains unique browser name values &
'result_user_count' contains 'sum of users' for each type of browser.
I have seen this solution, which works great for a single array. In my case I have 2 arrays ....
Any help is very much appreciated. Thanks

I'd suggest using an object. Assuming your 2 arrays will always match in length:
var browser_names = ["Firefox", "Maxthon", "Opera", "Opera", "Chrome", "Chrome", "Edge", "Firefox"]
var user_count = [3, 3, 3, 3, 7, 20, 94, 142]
var lib = {}
for (var i=0; i < browser_names.length; i++) {
if (lib[browser_names[i]] != undefined) {
lib[browser_names[i]] += user_count[i];
} else {
lib[browser_names[i]] = user_count[i];
}
}
This should give you the browser names and the cumulative user counts for each browser saved within object lib
Also, for the if conditional in the loop, you could also do:
for (var i=0; i < browser_names.length; i++) {
if (lib.hasOwnProperty(browser_names[i])) {
lib[browser_names[i]] += user_count[i];
} else {
lib[browser_names[i]] = user_count[i];
}
}
Also, I know your original question was an output to an array. You can easily loop through the keys of the object to get each of their respective browser names and user counts as well:
for (var k in lib) {
console.log(k); // Browser Names
console.log(lib[k]); // Their respective user counts
}

You could use a single loop and the help from an object as reference to the result arrays.
var browser_names = ["Firefox", "Maxthon", "Opera", "Opera", "Chrome", "Chrome", "Edge", "Firefox"],
user_count = [3, 3, 3, 3, 7, 20, 94, 142],
result_browser_names = [],
result_user_count = [];
browser_names.forEach(function (b, i) {
if (!(b in this)) {
this[b] = result_browser_names.push(b) - 1;
result_user_count.push(0);
}
result_user_count[this[b]] += user_count[i];
}, Object.create(null));
console.log(result_browser_names);
console.log(result_user_count);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Related

Sum every last index value with previous values in JS

I have an array:
array = {
"data": [
{ "value": [ 100, 13, 16 ] },
{ "value": [ 101, 14, 17 ] },
{ "value": [ 12, 15, 18 ] }
]
}
Which I am reformatting into a new array of just the columns:
const columnArray = jsonData.map( (current, index, arr) => {
let out = [];
for( let i = 0; i < current.value.length; i++ ) {
out.push( arr[ i ].value[ index ] );
}
return out;
});
// output
[
[ 100, 101, 12 ],
[ 13, 14, 15 ],
[ 16, 17, 18 ]
]
How would I re-write the columnArray mapping to do the column array and be able to sum from the previous value?
So the intended output from the original array would be:
[
[ 100, 201, 213 ],
[ 13, 27, 42 ],
[ 16, 33, 51 ]
]
I would also like the summing to be scalable (though it will always be in a 1:1 ratio). So if the data has 20 items, then each value will have 20 integers in that array too.
I have tried looping through but that didn't work as I only sum from the previous, not all the previous. And this wouldn't scale either:
const columnArray = jsonData.map( (current, index, arr) => {
let out = [];
for( let i = 0; i < current.value.length; i++ ) {
// dont touch first
if( i < 1 ) {
out.push( arr[ i ].value[ index ] );
} else {
out.push( arr[ i ].value[ index ] + arr[ i - 1 ].value[ index ] )
}
}
return out;
});
Instead of pushing the array element, add it to a variable accumulating the running totals, and push that.
const jsonData = [{
"value": [100, 13, 16]
},
{
"value": [101, 14, 17]
},
{
"value": [12, 15, 18]
}
];
const columnArray = jsonData.map((current, index, arr) => {
let out = [];
let total = 0;
for (let i = 0; i < current.value.length; i++) {
total += arr[i].value[index]
out.push(total);
}
return out;
});
console.log(columnArray);
or with a nested map():
const jsonData = [{
"value": [100, 13, 16]
},
{
"value": [101, 14, 17]
},
{
"value": [12, 15, 18]
}
];
const columnArray = jsonData.map((current, index, arr) => {
let total = 0;
return arr.map(el => total += el.value[index])
});
console.log(columnArray);
You're thinking this in the wrong way. You're storing the sum in the list, not anywhere else. So even tho your index is increasing, the resulting sum resides in the list, so to achieve your goal you have to save it in some variable then push the variable into the final list. Follow this code below:
const columnArray = array.data.map((current, index, arr) => {
let out = [];
let temp;
for (let i = 0; i < current.value.length; i++) {
// dont touch first
if (i < 1) {
temp = arr[i].value[index];
out.push(arr[i].value[index]);
} else {
temp = arr[i].value[index] + temp;
out.push(temp);
}
}
return out;
});
something like that...
const array0 = {
"data": [
{ "value": [ 100, 13, 16 ] },
{ "value": [ 101, 14, 17 ] },
{ "value": [ 12, 15, 18 ] }
]
}
const
rowCount = array0.data.reduce((c,{value})=>Math.max(c,value.length) ,0)
, arrResult = Array(rowCount).fill(0).map(x=>Array(array0.data.length).fill(0))
;
arrResult.forEach((_,i,arr)=>
{
array0.data[i].value.forEach((v,j)=>
{
arr[j][i] = v + (i? arr[j][i-1] : 0 )
})
})
console.log( arrResult)
.as-console-wrapper {max-height: 100%!important;top:0}

Javascript array contains/includes sub array

I need to check if an array contains another array. The order of the subarray is important but the actual offset it not important. It looks something like this:
var master = [12, 44, 22, 66, 222, 777, 22, 22, 22, 6, 77, 3];
var sub = [777, 22, 22];
So I want to know if master contains sub something like:
if(master.arrayContains(sub) > -1){
//Do awesome stuff
}
So how can this be done in an elegant/efficient way?
With a little help from fromIndex parameter
This solution features a closure over the index for starting the position for searching the element if the array. If the element of the sub array is found, the search for the next element starts with an incremented index.
function hasSubArray(master, sub) {
return sub.every((i => v => i = master.indexOf(v, i) + 1)(0));
}
var array = [12, 44, 22, 66, 222, 777, 22, 22, 22, 6, 77, 3];
console.log(hasSubArray(array, [777, 22, 22]));
console.log(hasSubArray(array, [777, 22, 3]));
console.log(hasSubArray(array, [777, 777, 777]));
console.log(hasSubArray(array, [42]));
var master = [12, 44, 22, 66, 222, 777, 22, 22, 22, 6, 77, 3];
var sub = [777, 22, 22];
console.log(master.join(',').includes(sub.join(',')))
//true
You can do this by simple console.log(master.join(',').includes(sub.join(','))) this line of code using include method
The simplest way to match subset/sub-array
const master = [12, 44, 22, 66, 222, 777, 22, 22, 22, 6, 77, 3];
const sub1 = [777, 44, 222];
const sub2 = [777, 18, 66];
sub1.every(el => master.includes(el)); // reture true
sub2.every(el => master.includes(el)); // return false
Just came up with quick thought , but efficiency depends on size of the array
var master = [12, 44, 22, 66, 222, 777, 22, 22, 22, 6, 77, 3];
var sub = [777, 22, 22];
if ((master.toString()).indexOf(sub.toString()) > -1 ){
//body here
}
It’s surprising how often this is implemented incorrectly.
What we’re looking for is a substring in the mathematical sense.
In mathematics, a sequence is an enumerated collection of objects in which repetitions are allowed and order matters.
In mathematics, a subsequence of a given sequence is a sequence that can be derived from the given sequence by deleting some or no elements without changing the order of the remaining elements.
A subsequence which consists of a consecutive run of elements from the original sequence, such as ⟨ B, C, D ⟩ from ⟨ A, B, C, D, E, F ⟩ is a substring.
Note that a “string”, here, can consist of any element and is not limited to Unicode code-point sequences.
Effectively all previous answers have one of many possible flaws:
The string concatenation approach (array1.toString().includes(array2.toString())) fails when your array elements have commas. (Example: [ "a", "b" ] does not contain [ "a,b" ]).
Some implementations check beyond array bounds. (Example: [ "3" ] does not contain [ "3", undefined ], just because array[1] reports undefined for both).
Some implementations fail to handle repetition correctly.
Some implementations aren’t checking for substrings (in the mathematical sense) correctly, but for subsets or subsequences or something else.
Some implementations don’t account for the empty array. The empty string is the substring of every string.
Check if an array constitutes a “substring” of another array
Right off the bat, this handles the empty array correctly.
Then, it builds a list of candidate starting indexes by matching against the first element of the potential subarray.
Find the first candidate where every element of the slice matches index by index with the full array, offset by the candidate starting index.
The checked index also has to exist within the full array, hence Object.hasOwn.
const isSubArray = (full, slice) => {
if(slice.length === 0){
return true;
}
const candidateIndexes = full
.map((element, fullIndex) => ({
matched: element === slice[0],
fullIndex
}))
.filter(({ matched }) => matched),
found = candidateIndexes
.find(({ fullIndex }) => slice.every((element, sliceIndex) => Object.hasOwn(full, fullIndex + sliceIndex) && element === full[fullIndex + sliceIndex]));
return Boolean(found);
};
console.log(isSubArray([], []) === true);
console.log(isSubArray([ 0 ], []) === true);
console.log(isSubArray([ 0, 1, 2 ], [ 1, 2 ]) === true);
console.log(isSubArray([ 0, 1, 1, 2 ], [ 0, 1, 2 ]) === false);
console.log(isSubArray([ 2, 1 ], [ 1, 2 ]) === false);
console.log(isSubArray([ 1, 2, 3 ], [ 2, 3, undefined ]) === false);
console.log(isSubArray([ 0, 1, 1, 2, 3 ], [ 1, 1, 2 ]) === true);
console.log(isSubArray([ 0, 1, 1, 2, 3 ], [ 1, 2 ]) === true);
console.log(isSubArray([ 0, 1, 1, 2, 3 ], [ 0, 1, 1, 1 ]) === false);
console.log(isSubArray([ "a", "b" ], [ "a,b" ]) === false);
.as-console-wrapper { max-height: 100% !important; top: 0; }
This has quadratic complexity, yes.
There might be more efficient implementations using Trees or Ropes.
You might also want to research some efficient substring search algorithms and try to apply them to this problem.
Get the index of the found “substring”, or -1 if not found
It’s basically the same code, but with return true; replaced by return 0;, and return Boolean(found); replaced by return found?.fullIndex ?? -1;.
const findSubArrayIndex = (full, slice) => {
if(slice.length === 0){
return 0;
}
const candidateIndexes = full
.map((element, fullIndex) => ({
matched: element === slice[0],
fullIndex
}))
.filter(({ matched }) => matched),
found = candidateIndexes
.find(({ fullIndex }) => slice.every((element, sliceIndex) => Object.hasOwn(full, fullIndex + sliceIndex) && element === full[fullIndex + sliceIndex]));
return found?.fullIndex ?? -1;
};
console.log(findSubArrayIndex([], []) === 0);
console.log(findSubArrayIndex([ 0 ], []) === 0);
console.log(findSubArrayIndex([ 0, 1, 2 ], [ 1, 2 ]) === 1);
console.log(findSubArrayIndex([ 0, 1, 1, 2 ], [ 0, 1, 2 ]) === -1);
console.log(findSubArrayIndex([ 2, 1 ], [ 1, 2 ]) === -1);
console.log(findSubArrayIndex([ 1, 2, 3 ], [ 2, 3, undefined ]) === -1);
console.log(findSubArrayIndex([ 0, 1, 1, 2, 3 ], [ 1, 1, 2 ]) === 1);
console.log(findSubArrayIndex([ 0, 1, 1, 2, 3 ], [ 1, 2 ]) === 2);
console.log(findSubArrayIndex([ 0, 1, 1, 2, 3 ], [ 0, 1, 1, 1 ]) === -1);
console.log(findSubArrayIndex([ "a", "b" ], [ "a,b" ]) === -1);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Semi-acceptable alternative: JSON
JSON-encoding both arrays might be a viable strategy as well.
Here, the surrounding […] of the potential subarray need to be removed, then an includes will tell you if the JSON string is included in the other JSON string.
This works — as opposed to the simple string concatenation or join approach — because JSON has delimiters that cannot appear verbatim in the encoded elements; if they do appear in the original elements, they’d be correctly escaped.
The caveat is that this won’t work for values that are not encodable in JSON.
const isSubArray = (full, slice) => JSON.stringify(full)
.includes(JSON.stringify(slice).replaceAll(/^\[|\]$/g, ""));
console.log(isSubArray([], []) === true);
console.log(isSubArray([ 0 ], []) === true);
console.log(isSubArray([ 0, 1, 2 ], [ 1, 2 ]) === true);
console.log(isSubArray([ 0, 1, 1, 2 ], [ 0, 1, 2 ]) === false);
console.log(isSubArray([ 2, 1 ], [ 1, 2 ]) === false);
console.log(isSubArray([ 1, 2, 3 ], [ 2, 3, undefined ]) === false);
console.log(isSubArray([ 0, 1, 1, 2, 3 ], [ 1, 1, 2 ]) === true);
console.log(isSubArray([ 0, 1, 1, 2, 3 ], [ 1, 2 ]) === true);
console.log(isSubArray([ 0, 1, 1, 2, 3 ], [ 0, 1, 1, 1 ]) === false);
console.log(isSubArray([ "a", "b" ], [ "a,b" ]) === false);
.as-console-wrapper { max-height: 100% !important; top: 0; }
If the order is important, it has to be an actually sub-array (and not the subset of array) and if the values are strictly integers then try this
console.log ( master.join(",").indexOf( subarray.join( "," ) ) == -1 )
for checking only values check this fiddle (uses no third party libraries)
var master = [12, 44, 22, 66, 222, 777, 22, 22, 22, 6, 77, 3];
var sub = [777, 22, 22];
function isSubset( arr1, arr2 )
{
for (var i=0; i<arr2.length; i++)
{
if ( arr1.indexOf( arr2[i] ) == -1 )
{
return false;
}
}
return true;
}
console.log( isSubset( master, sub ) );
There are faster options explained here as well.
EDIT
Misunderstood question initially.
function arrayContainsSub(arr, sub) {
var first = sub[0],
i = 0,
starts = [];
while (arr.indexOf(first, i) >= 0) {
starts.push(arr.indexOf(first, i));
i = arr.indexOf(first, i) + 1;
}
return !!starts
.map(function(start) {
for (var i = start, j = 0; j < sub.length; i++, j++) {
if (arr[i] !== sub[j]) {
return false;
}
if (j === sub.length - 1 && arr[i] === sub[j]) {
return true;
}
};
}).filter(function(res) {
return res;
}).length;
}
This solution will recursively check all available start points, so points where the first index of the sub has a match in the array
Old Answer Kept in case useful for someone searching.
if(master.indexOf(sub) > -1){
//Do awesome stuff
}
Important to remember that this will only match of master literally references sub. If it just contains an array with the same contents, but references a different specific object, it will not match.
You can try with filter and indexOf like this:
Note: This code works in case we do not cover the order in sub array.
Array.prototype.arrayContains = function (sub) {
var self = this;
var result = sub.filter(function(item) {
return self.indexOf(item) > -1;
});
return sub.length === result.length;
}
Example here.
UPDATED: Return index of sub array inside master (cover order in sub array)
Array.prototype.arrayContains = function(sub) {
var first;
var prev;
for (var i = 0; i < sub.length; i++) {
var current = this.indexOf(sub[i]);
if (current > -1) {
if (i === 0) {
first = prev = current;
continue;
} else {
if (++prev === current) {
continue;
} else {
return -1;
}
}
} else {
return -1;
}
}
return first;
}
Demo: here
For this answer, I am preserving the order of sub-array. Means, the elements of sub-array should be in Consecutive order. If there is any extra element while comparing with the master, it will be false.
I am doing it in 3 steps:
Find the index of the first element of sub in the master and store it an array matched_index[].
for each entry in matched_index[] check if each element of sub is same as master starting from the s_index. If it doesn't match then return false and break the for loop of sub and start next for-loop for next element in matched_index[]
At any point, if the same sub array is found in master, the loop will break and return true.
function hasSubArray(master,sub){
//collect all master indexes matching first element of sub-array
let matched_index = []
let start_index = master.indexOf(master.find(e=>e==sub[0]))
while(master.indexOf(sub[0], start_index)>0){
matched_index.push(start_index)
let index = master.indexOf(sub[0], start_index)
start_index = index+1
}
let has_array //flag
for(let [i,s_index] of matched_index.entries()){
for(let [j,element] of sub.entries()){
if(element != master[j+s_index]) {
has_array = false
break
}else has_array = true
}
if (has_array) break
}
return has_array
}
var master = [12, 44, 22, 66, 222, 777, 22, 22, 22, 6, 77, 3];
console.log(hasSubArray(master, [777, 22, 22]));
console.log(hasSubArray(master, [777, 22, 3]));
console.log(hasSubArray(master, [777, 777, 777]));
console.log(hasSubArray(master, [44]));
console.log(hasSubArray(master, [22, 66]));
I had a similar problem and resolved it using sets.
function _hasSubArray( mainArray, subArray )
{
mainArray = new Set( mainArray );
subArray = new Set( subArray );
for ( var element of subArray )
{
if ( !mainArray.has( element ) )
{
return false;
}
}
return true;
}
If run this snippet below it should work
x = [34, 2, 4];
y = [2, 4];
y.reduce((included, num) => included && x.includes(num), true);
EDIT:
#AlexanderGromnitsky You are right this code is incorrect and thank you for the catch! The above code doesn't actually do what the op asked for. I didn't read the question close enough and this code ignores order. One year later here is what I came up with and hopefully this may help someone.
var master = [12, 44, 22, 66, 222, 777, 22, 22, 22, 6, 77, 3];
var sub = [777, 22, 22];
var is_ordered_subset = master.join('|').includes(sub.join('|'))
This code is somewhat elegant and does what op asks for. The separator doesn't matter as long as its not an int.
async function findSelector(a: Uint8Array, selector: number[]): Promise<number> {
let i = 0;
let j = 0;
while (i < a.length) {
if (a[i] === selector[j]) {
j++;
if (j === selector.length) {
return i - j + 1;
}
} else {
j = 0;
}
i++;
}
return -1;
}
Try using every and indexOf
var mainArr = [1, 2, 3, 4, 5]
var subArr = [1, 2, 3]
function isSubArray(main, sub) {
return sub.every((eachEle) => {
return (main.indexOf(eachEle) + 1);
});
}
isSubArray(mainArr, subArr);

Javascript Populate key value with value is an array

I want to iterate over a JSON in javasacript and create something like this as output
{
"seriesData": [
{
"name": "John",
"data": [
5,
3,
4
]
},
{
"name": "Jane",
"data": [
2,
2,
3
]
},
{
"name": "Joe",
"data": [
3,
4,
4
]
}
]
}
So, I essentially need to add values in data array for each key inside my for loop.
Input looks like:
{"Records":[{"name":"Jan'10","users":[{"name":"John","y":5},{"name":"Jane","y":2},{"name":"Joe","y":3}]},{"name":"Jan'10","users":[{"name":"John","y":3},{"name":"Jane","y":2},{"name":"Joe","y":4}]},{"name":"Jan'10","users":[{"name":"John","y":4},{"name":"Jane","y":3},{"name":"Joe","y":4}]}]};
Can someone please suggest how can this be achieved.
you could try something like this:
var dataList = {};
function addData(name){
if( dataList[name] == undefined)
dataList[name] = [];
for (var i = 1; i < arguments.length; i++) {
dataList[name].push(arguments[i]);
}
}
function packData(){
var pack = []
for(var e in dataList){
pack.push({
name: e,
data:dataList[e].sort(function(a,b){return a-b})
});
}
return pack;
}
addData("Joe", 1);
addData("Jan", 2, 10);
addData("Joe", 3, 5, 10, 18, 500);
addData("Jan", 4);
addData("Joe", 5);
addData("Jan", 6);
console.log( packData() );
use addData(name, data); to append data to a name and afterwards pack this data with packData()
EDIT:
Sry switched to PHP for a while... fixed the script XD

Grouping consecutive elements together using Javascript

I have an array of elements like so:
messages[i], where messages[i] may only exist for certain values of i. For instance messages[0] and messages[2] may exist but not messages[1].
Now I would like to group together elements with continuous indices, for example if the indices for which messages existed were:
2, 3, 4, 5, 8, 9, 12, 13, 14, 15, 16, 17, 20
I would like to group them like so:
2, 3, 4, 5
8, 9
12, 13, 14, 15, 16, 17
20
What would be an effective way to do so using Javascript?
EDIT:
for (i = 0; i < messages.length; i++) {
if (messages[i].from_user_id == current_user_id) {
// group the continuous messages together
} else {
//group these continuous messages together
}
}
You can use a counter variable which has to be incremented and the difference between the index and the consecutive elements are the same, group them in a temporary array. If the difference is varies for two consecutive array elements, the temporary element has to be moved to the result and the temporary array has to be assigned a new array object.
var array = [2, 3, 4, 5, 8, 9, 12, 13, 14, 15, 16, 17, 20];
var result = [], temp = [], difference;
for (var i = 0; i < array.length; i += 1) {
if (difference !== (array[i] - i)) {
if (difference !== undefined) {
result.push(temp);
temp = [];
}
difference = array[i] - i;
}
temp.push(array[i]);
}
if (temp.length) {
result.push(temp);
}
console.log(result);
# [ [ 2, 3, 4, 5 ], [ 8, 9 ], [ 12, 13, 14, 15, 16, 17 ], [ 20 ] ]
Given :
var data = [ undefined, undefined, 2, 3, 4, 5,
undefined,undefined, 8, 9,
undefined, undefined, 12, 13, 14, 15, 16, 17,
undefined, undefined, 20];
(or the almost equivalent array where the undefined elements don't exist at all, but where the defined elements have the same indices as above) this reduce call will return a two-dimensional array where each top level element is the contents of the original array, grouped by contiguously defined entries:
var r = data.reduce(function(a, b, i, v) {
if (b !== undefined) { // ignore undefined entries
if (v[i - 1] === undefined) { // if this is the start of a new run
a.push([]); // then create a new subarray
}
a[a.length - 1].push(b); // append current value to subarray
}
return a; // return state for next iteration
}, []); // initial top-level array
i.e. [[ 2, 3, 4, 5], [8, 9], [12, 13, 14, 15, 16, 17], [20]]
NB: this could also be written using a .forEach call, but I like .reduce because it requires no temporary variables - all state is encapsulated in the function parameters.
I would iterate through the list, and if you find an element at messages[i], add i to a list of mins. Then, once you don't find an element at messages[j], and j to a list of maxes.
Then you will have two lists (or one, if you use a container, as I probably would) that contains the start and stop indexes of the groups.
Another approach would be something like this. I'm using a library called lodash for my array manipulation.
Basically I'm sorting the array in ascending order. And then for every increment, I'm storing the current element to a temporary array and comparing the last value of that array to the current element if they are in sequence if not I push the values of the temporary array to my result array and so on. If my loop reaches the end I just push the values of my temporary array to my results array.
var _ = require('lodash');
var arr = [2, 3, 4, 5, 8, 9, 12, 13, 14, 15, 16, 17, 20];
arr = _.sortBy(arr, function (o) {
return o;
});
var tmp = [];
var res = [];
for (var i = 0; i < arr.length; i++) {
if (tmp.length === 0) {
tmp.push(arr[i]);
}
else {
var lastEl = _.last(tmp);
if ((lastEl + 1) === arr[i]) {
tmp.push(arr[i]);
}
else {
res.push(tmp);
tmp = [];
tmp.push(arr[i]);
}
if (i === (arr.length - 1)) {
res.push(tmp);
tmp = [];
}
}
}
// Outputs: [ [ 2, 3, 4, 5 ], [ 8, 9 ], [ 12, 13, 14, 15, 16, 17 ], [ 20 ] ]
const cluster = (arr, tmp = [], result = []) =>
(result = arr.reduce((acc, c, i) =>
(!tmp.length || c === (arr[i-1]+1)
? (tmp.push(c), acc)
: (acc.push(tmp), tmp = [c], acc))
, []), tmp.length ? (result.push(tmp), result) : result)
console.log(cluster([2, 3, 4, 5, 8, 9, 12, 13, 14, 15, 16, 17, 20]))

Javascript sorting caption array the same way as according data array

I have a sorting problem in javascript, I need to sort an array and sort the captions (saved in another array) in the same order (descending), how can I sort them the same way?
For the clarity of my post I will reduce it to a basic example:
var arr = Array(9, 5, 11, 2, 3);
var arrCaptions = Array("some text","another bit of text","three", "four?", "maybe five?");
Now I want to run a kind of sort mechanism that sorts the arrCaptions array the same way as the arr array, so as result you would get this:
var arrResult = Array(11, 9, 5, 3, 2);
var arrCaptionsResult = Array("three", "some text" ,"another bit of text", "maybe five?", "four?");
What I have tried so far doesn't work at all:
var numlist = Array(9, 5, 11, 2, 3);
var list = Array("four?","maybe five?","another bit of text","some text","three");
var resultnumlist = Array();
var resultlist = Array();
resultnumlist[0] = numlist[0];
resultlist[0] = list[0];
for (i = 0; i < list.length; i++) {
var i2 = list.length - 1;
while (numlist[i] < resultnumlist[i2]) {
i2--;
}
resultnumlist.splice(i2 - 1,0,numlist[i]);
resultlist.splice(i2 - 1,0,list[i]);
}
Bundle them together in an object.
var stuff = [{
id: 9,
text: "text hello"
}, {
id: 5,
text: "text world"
}, {
id: 11,
text: "text test"
}, {
id: 2,
text: "text 23"
}];
stuff.sort( function( a, b ) {
return a.id - b.id; //Objects are sorted ascending, by id.
});
The result is:
[{
"id": 2,
"text": "text 23"
}, {
"id": 5,
"text": "text world"
}, {
"id": 9,
"text": "text hello"
}, {
"id": 11,
"text": "text test"
}]
How about combining them into one array? Then you can sort this array based on the value of the numbers, and the captions get sorted in tandem:
//Your arrays
var arr = [9, 5, 11, 2, 3];
var arrCaptions = ["some text", "another bit of text", "three", "four?", "maybe five?"];
//The composite array
var composite = arr.map(function(v, i) {
return {
rank: v,
caption: arrCaptions[i]
};
});
//Sort this array
composite.sort(function(a, b) {
return a.rank - b.rank;
});
console.log(composite);
Here is a demonstration: http://jsfiddle.net/cFDww/
Here is your modified code:
var numlist = Array(9, 5, 11, 2, 3);
var list = Array("nine?","maybe five?","another bit of 11","some 2","three");
var resultnumlist = new Array();
var resultlist = new Array();
for (i = 0; i < list.length; i++) {
var i2 = resultnumlist.length - 1;
while ((numlist[i] < resultnumlist[i2]) && (i2 >= 0)) {
i2--;
}
i2++;
resultnumlist.splice(i2, 0, numlist[i]);
resultlist.splice(i2, 0, list[i]);
}
console.log(resultlist);
console.log(resultnumlist);
See it working

Categories