Count how many identical elements in 2 arrays occur - javascript

I have a form and as a result of that form I have two arrays - one for personA's details and one for personB's details. One part of the form is a bunch of checkboxes of dates - the dates are a fixed price, but booking for two on the same date is a reduced price.
What I want to do is compare personA's array with personB's array and for any duplicates issue a reduced rate.
The rate will be calculated into two variables - total full price dates (in £s) and total reduced price dates (in £s).
Here is my code so far (this occurs on the checkboxes onclick):
function processDates(){
var contentsA, valsA = [], dates_A = document.forms['registerForm']['personADates[]'];
for(var iA=0,elmA;elmA = dates_A[iA];iA++) {
if(elmA.checked) {
valsA.push(elmA.value);
}
}
contentsA = valsA.join(', ');
var contentsB, valsB = [], dates_B = document.forms['registerForm']['personBDates[]'];
for(var iB=0,elmB;elmB = dates_B[iB];iB++) {
if(elmB.checked) {
valsB.push(elmB.value);
}
}
contentsB = valsB.join(', ');
}

With my own http://phrogz.net/JS/ArraySetMath.js you could do:
// If the original order of the elements is not important
var common = array1.intersect( array2 );
// If the original order of the elements is important
var common = array1.unsortedIntersect( array2 );
With the larger JS.Set you could do:
// If the original order of the elements is not important
var common = (new JS.SortedSet(array1)).intersect(new JS.SortedSet(array2));
// If the original order of the elements is important
var common = (new JS.Set(array1)).intersect(new JS.Set(array2));
It is not clear to me what the values in your arrays actually are; are these dates entered by the user in plain text? If so, you'll want to ensure that they are normalized so that they are comparable and guaranteed to match.
If these are more than simple comparable objects (e.g. instead of String or Date instances you are creating arrays complex Objects) then my library allows you to supply a comparison function so you can determine which are equal. See the library for more details on this.

Instead of using an array you could use an object (warning... untested code):
function processDates(){
var valsA = {}, dates_A = document.forms['registerForm']['personADates[]'];
for(var iA=0,elmA;elmA = dates_A[iA];iA++) {
if(elmA.checked) {
valsA[elmA.value] = 1; // Store values
}
}
var samedate = [];
var dates_B = document.forms['registerForm']['personBDates[]'];
for(var iB=0,elmB;elmB = dates_B[iB];iB++) {
if(elmB.checked) {
if (valsB[elmB.value])
{
// Here we found a date that's present in both
samedate.push(elmB.value);
}
}
}
// Here samedate is a list of all dates listed in both A and B
}

If functional javascript is an option:
_.sum = function(array) {
return _.reduce(array, function(memo, val) {
return memo + val;
}, 0);
};
var duplicates = _.intersect(valsA, valsB);
var fullPrice = _.sum(valsA.concat(valsB));
var reducedPrice = fullPrice - discountScalar * _.sum(duplicates);
Relies on underscore.js for easy cross browser implentation of functional methods. Most of these can be implemented with array.reduce & array.map on modern browsers.

Related

how can I filter an array without losing the index?

I have two really long arrays containing "picture names" and "picture files". The first one represents the actual name of the pictures, while the second one is just the file name. For example:
picturenames[0] = '0 - zero';
picturenames[1] = '1 - one';
picturenames[2] = '1 o\'clock';
...
picturefiles[0] = 'numbers-zero.jpg';
picturefiles[1] = 'numbers-one.jpg';
picturefiles[2] = 'time-1.jpg';
...
I have about 1000 items in each array in several languages (the picture files are always the same). I'm "recycling" these arrays from the previous application to save some time and avoid rewriting everything anew.
Desirable functionality: using the user's input in a textbox I want to filter the picturenames array and then show the correspondant picturefiles image.
The issue I'm facing: when I filter the picturenames array I lose the index and I can't "reach" the picture file name.
This is the code I'm using to filter the picturenames array.
var matches = picturenames.filter(function(windowValue){
if(windowValue) {
return windowValue.indexOf(textToFindLower) >= 0;
}
});
What would be the best way to do this?
UPDATE: the solution proposed by Ahmed is the best one, but for time reasons and negligible performance issues I'm just using a for loop to search trough the array, as follows:
var matchesCounter = new Array();
for (i = 0; i < picturenames.length; i++) {
if (picturenames[i].indexOf(textToFindLower) >= 0) {
matchesCounter.push(i);
}
}
console.log(matchesCounter);
for (i = 0; i < matchesCounter.length; i++) {
console.log(picturenames[i]);
console.log(picturefiles[i]);
}
Try this:
const foundIndicies = Object.keys(picturenames).filter(pictureName => {
pictureName.includes(textToFindLower)
});
// reference picturefiles[foundIndicies[0]] to get the file name
Though, it would be far nicer to have both the name and the file in a single object, like so:
const pictures = [
{
name: '0 - zero',
file: 'numbers-zero.jpg',
},
{
name: '1 - one',
file: 'numbers-one.jpg',
}
];
const foundPictures = pictures.filter(picture => picture.name.includes('zero'));
if (foundPictures[0]) console.log(foundPictures[0].file);
You can add one property index during the filtering time, then later on you can use the index.
var matches = picturenames.filter(function(windowValue, index){
if(windowValue) {
windowValue.index = index;
return windowValue.comparator(textToFindLower) >= 0;// Need to define comparator function
}
});
Later on you can access by using like follows:
picturefiles[matches[0].index]
However, the solution will work on object, not primitive type string.
If your data type is string, then you have to convert as object and put the string as a property value like name. The snippet is given below:
var picturenames = [];
var picturefiles = [];
picturenames.push({name:'0 - zero'});
picturenames.push({name:'1 - one'});
picturenames.push({name:'1 o\'clock'});
picturefiles.push({name:'numbers-zero.jpg'});
picturefiles.push({name:'numbers-one.jpg'});
picturefiles.push({name: 'time-1.jpg'});
var textToFindLower = "0";
var matches = picturenames.filter(function(windowValue, index){
if(windowValue) {
windowValue.index = index;
return windowValue.name.indexOf(textToFindLower) >= 0;
}
});
console.log(matches);

Reorganizing multidimensional arrays based on multiple value characteristics in JavaScript?

I'm having trouble organizing this data the way I would like it to. On my pages, a few things happen that I know work...
Some PHP spits out a multidimensional associative array. The top level of this array is an array of regions. Each region is an array of timezones.
Some more PHP creates a second multidimensional associative array. The top level of this array is an array of regions. Each region is an array of UTC offsets.
Both arrays are generated in the same order from the same data. This means that $offsets["region"][0] will have be based on the same timezone as $timezones["region"][0].
Both arrays are encoded into JSON and passed to my JavaScript.
I have the following JavaScript code...
var tempCurrentTimezoneArray = timezoneArray[ $("select[name='region_selector']").val() ];
var tempCurrentOffsetArray = timezoneOffsetArray[ $("select[name='region_selector']").val() ];
var groupedTimezones = {};
var groupedOffsets = {};
for (counter = 0; counter < tempCurrentOffsetArray.length; counter++) {
significantOffset = tempCurrentOffsetArray[counter].substr(tempCurrentOffsetArray[counter].length - 2);
if (!(significantOffset in groupedTimezones)) {
groupedTimezones[significantOffset] = [];
groupedOffsets[significantOffset] = [];
}
groupedTimezones[significantOffset].push(tempCurrentTimezoneArray[counter]);
groupedOffsets[significantOffset].push(tempCurrentOffsetArray[counter]);
}
var offsetArray = [];
for (var property in groupedTimezones) {
if (!groupedTimezones.hasOwnProperty(property)) {
continue;
}
groupedTimezones[property].sort();
groupedOffsets[property].sort();
offsetArray.push(parseInt(property));
}
offsetArray.sort();
var currentTimezoneArray = [];
var currentOffsetArray = [];
for (counter = 0; counter < offsetArray.length; counter++) {
currentTimezoneArray = currentTimezoneArray.concat(groupedTimezones[offsetArray[counter]]);
currentOffsetArray = currentOffsetArray.concat(groupedOffsets[offsetArray[counter]]);
}
In the top two lines I remove all of the timezone data not pertaining to the region selected on the page. This means that I am left with 2 single-dimensional arrays. Any given index of either array relates directly to the other array. I.E....
tempCurrentOffsetArray[0] is the UTC offset of the timezone found at tempCurrentTimezoneArray[0].
The rest of this code is intended to complete the following tasks...
Group timezones and offsets by their UTC offset.
Organize each offset group in alphabetical order.
Create two arrays where values are organized first by UTC offset and second by alphabetical order.
The problem I'm having is that on some regions I receive almost perfect listings,and on others I receive some listings with a seemingly random number of undefined values, and I'm not sure why. Can anyone identify the syntactical or logical errors in my code?
JSON of tempCurrentTimezoneArray input data here
JSON of tempCurrentOffsetArray input data here
You think still too complicated. It is a mess to keep these two Arrays in sync, better use one Array with objects.
var region_selector = $("select[name='region_selector']").val();
var tempCurrentTimezoneArray = timezoneArray[ region_selector ];
var tempCurrentOffsetArray = timezoneOffsetArray[ region_selector ];
//consolidate the Arrays
var data = []; //create a new Array `data`
for(var i = tempCurrentOffsetArray.length; i--; ){
//write into Array `data` at index `i` an object, containing these properties:
//`timezone`, `offset` and `offsetValue`, and their respective values
data[i] = {
timezone: tempCurrentTimezoneArray[i],
offset: tempCurrentOffsetArray[i],
//the + at the beginning converts the value behind that into a Number, like parseFloat() would do
offsetValue: +tempCurrentOffsetArray[i].match(/^GMT([+-]\d+(?:\.\d+)?)$/)[1]
}
}
//sorter-function for data to sort the values by offsetValue ASC first, then by timezone ASC
function sortedByOffset(a, b){
return a.offsetValue - b.offsetValue || a.timezone.localeCompare(b.timezone);
}
//you should do this as late as possible, usually after the filtering
data.sort(sortedByOffset);
If you insist on the two output-Arrays
var currentTimezoneArray = data.map(d => d.timezone);
var currentOffsetArray = data.map(d => d.offset);
otherwise this is imo more flexible
//utilities to fetch a property off the object
var getTimezone = d => d.timezone;
//aka function getTimezone(d){ return d.timezone }
var getOffset = d => d.offset;
//aka function getOffset(d){ return d.offset }
//example usages:
data.filter(d => d.offset === "GMT-5").map( getTimezone );
data.filter(d => d.offsetValue >= -2 && d.offsetValue <= -5 ).map( getOffset );
taking the first example; thinking in terms of a SQL-statement this would be
SELECT timezone FROM data WHERE offset = "GMT-5"
get me the timezone-values for each entry where the offset is GMT-5
you start with an Array containsing all values data then you get the subset you are interested in (in this case every entry, with the offset "GMT-5") by filtering.
Now you have an Array containing all values you are intersted in, but still the whole objects; like a SELECT * FROM ...
the map() function calls the function getTimezone() on every entry in this subset and returns another Array containing only the timezone-values.
The second example defines a range for the filter (every entry from GMT-2 to and including GMT-5 and every GMT in between) and returns for these entries the offset-protperty.
I discovered the issue with my code. There were actually three issues the first being on line 6. After looking over the data one more time I realized that some of the values had offsets that were floating point integers or had more than two significant digits. The new line 6 is...
significantOffset = tempCurrentOffsetArray[counter].replace(/[^\d.-]/g, '');
The second issue with my code also had to do with parsing floating integers. On line 21 we need to use parseFloat instead of parseInt. The new line 21 is...
offsetArray.push(parseFloat(property));
The third issue lies on line 23. sort() needs to be told how to sort the integers. This is the new line 23...
offsetArray.sort(function(a, b){return a-b});
The final code looks like this...
var tempCurrentTimezoneArray = timezoneArray[ $("select[name='region_selector']").val() ];
var tempCurrentOffsetArray = timezoneOffsetArray[ $("select[name='region_selector']").val() ];
var groupedTimezones = {};
var groupedOffsets = {};
for (counter = 0; counter < tempCurrentOffsetArray.length; counter++) {
significantOffset = tempCurrentOffsetArray[counter].replace(/[^\d.-]/g, '');
if (!(significantOffset in groupedTimezones)) {
groupedTimezones[significantOffset] = [];
groupedOffsets[significantOffset] = [];
}
groupedTimezones[significantOffset].push(tempCurrentTimezoneArray[counter]);
groupedOffsets[significantOffset].push(tempCurrentOffsetArray[counter]);
}
var offsetArray = [];
for (var property in groupedTimezones) {
if (!groupedTimezones.hasOwnProperty(property)) {
continue;
}
groupedTimezones[property].sort();
groupedOffsets[property].sort();
offsetArray.push(parseFloat(property));
}
offsetArray.sort(function(a, b){return a-b});
var currentTimezoneArray = [];
var currentOffsetArray = [];
for (counter = 0; counter < offsetArray.length; counter++) {
currentTimezoneArray = currentTimezoneArray.concat(groupedTimezones[offsetArray[counter]]);
currentOffsetArray = currentOffsetArray.concat(groupedOffsets[offsetArray[counter]]);
}

How to create multiple objects based on dynamic data?

Basically what i'm doing, is trying to create my own steam market JSON, by HTML parsing.
Example of how I'm currently doing that :
var url = 'http://steamcommunity.com/market/search?appid=730'
var itemDiv = $("<div></div>")
$.get(url).success(function(r){
data = $(r).find('stuff i need')
itemDiv.append(data)
})
and now say I wanted to find names of the items in the div, i would do something like :
itemDiv.find('x').each(function(){
var name = $(this).find("y").text()
// console.log(name) [or do whatever is needed ect]
})
As I mentioned before, I need to return objects based on that data in the format of:
var item = {name:"",price:0}
However, things like price will always be changing.
Based on the data thats in the div, the final product would look along the lines of :
var x = {name:"a",price:1}
var x2 = {name:"a2",price:2}
How do I go about doing this? I thought maybe i could store the data in an array, and then do something like
for(x in y){
return object
}
or something along those lines.
Sorry if this seems like a bonehead question, I'm pretty new to javascript.
clarification: i'm trying to figure out how to return multiple objects based on the data inside the div.
Here is the code that builds an array of objects based on two arrays (assuming they are of equal length).
function buildStocks() {
// Names and prices can also be passed as function arguments
var names = ['a', 'b', 'c'];
var prices = [1, 2, 3];
var result = []; // Array of these objects
for (var i = 0; i < names.length; i++) {
result.push({
name: names[i],
price: prices[i]
});
}
return result;
}

Dynamically create a two dimensional Javascript Array

Can someone show me the javascript I need to use to dynamically create a two dimensional Javascript Array like below?
desired array contents:
[["test1","test2","test3","test4","test5"],["test6","test7","test8","test9","test10"]]
current invalid output from alert(outterArray):
"test6","test7","test8","test9","test10","test6","test7","test8","test9","test10"
JavaScript code:
var outterArray = new Array();
var innerArray = new Array();
var outterCount=0;
$something.each(function () {
var innerCount = 0;//should reset the inner array and overwrite previous values?
$something.somethingElse.each(function () {
innerArray[innerCount] = $(this).text();
innerCount++;
}
outterArray[outterCount] = innerArray;
outterCount++;
}
alert(outterArray);
This is pretty cut and dry, just set up a nested loop:
var count = 1;
var twoDimensionalArray =[];
for (var i=0;i<2;i++)
{
var data = [];
for (var j=0;j<5;j++)
{
data.push("Test" + count);
count++;
}
twoDimensionalArray.push(data);
}
It sounds like you want to map the array of text for each $something element into an outer jagged array. If so then try the following
var outterArray = [];
$something.each(function () {
var innerArray = [];
$(this).somethingElse.each(function () {
innerArray.push($(this).text());
});
outterArray.push(innerArray);
});
alert(outterArray);
A more flexible approach is to use raw objects, they are used in a similar way than dictionaries. Dynamically expendables and with more options to define the index (as string).
Here you have an example:
var myArray = {};
myArray[12]="banana";
myArray["superman"]=123;
myArray[13]={}; //here another dimension is created
myArray[13][55]="This is the second dimension";
You don't need to keep track of array lengths yourself; the runtime maintains the ".length" property for you. On top of that, there's the .push() method to add an element to the end of an array.
// ...
innerArray.push($(this).text());
// ...
outerArray.push(innerArray);
To make a new array, just use []:
innerArray = []; // new array for this row
Also "outer" has only one "t" :-)
[SEE IT IN ACTION ON JSFIDDLE] If that $something variable is a jQuery search, you can use .map() function like this:
var outterArray = [];
var outterArray = $('.something').map(function() {
// find .somethingElse inside current element
return [$(this).find('.somethingElse').map(function() {
return $(this).text();
}).get()]; // return an array of texts ['text1', 'text2','text3']
}).get(); // use .get() to get values only, as .map() normally returns jQuery wrapped array
// notice that this alert text1,text2,text3,text4,text5,text6
alert(outterArray);​
// even when the array is two dimensional as you can do this:
alert(outterArray[0]);
alert(outterArray[1]);
HTML:
<div class="something">
<span class="somethingElse">test1</span>
<span class="somethingElse">test2</span>
<span class="somethingElse">test3</span>
</div>
<div class="something">
<span class="somethingElse">test4</span>
<span class="somethingElse">test5</span>
<span class="somethingElse">test6</span>
</div>
Here you can see it working in a jsFiddle with your expected result: http://jsfiddle.net/gPKKG/2/
I had a similar issue recently while working on a Google Spreadsheet and came up with an answer similar to BrianV's:
// 1st nest to handle number of columns I'm formatting, 2nd nest to build 2d array
for (var i = 1; i <= 2; i++) {
tmpRange = sheet.getRange(Row + 1, Col + i, numCells2Format); // pass/fail cells
var d2Arr = [];
for (var j = 0; j < numCells2Format; j++) {
// 1st column of cells I'm formatting
if ( 1 == i) {
d2Arr[j] = ["center"];
// 2nd column of cells I'm formatting
} else if ( 2 == i ) {
d2Arr[j] = ["left"];
}
}
tmpRange.setHorizontalAlignments( d2Arr );
}
So, basically, I had to make the assignment d2Arr[index]=["some string"] in order to build the multidimensional array I was looking for. Since the number of cells I wanted to format can change from sheet to sheet, I wanted it generalized. The case I was working out required a 15-dimension array. Assigning a 1-D array to elements in a 1-D array ended up making the 15-D array I needed.
you can use Array.apply
Array.apply(0, Array(ARRAY_SIZE)).map((row, rowIndex) => {
return Array.apply(0, Array(ARRAY_SIZE)).map((column, columnIndex) => {
return null;
});
});`

Which is faster for finding element in javascript array?

I'm a noob and wrote a whole program without knowing the easy way to find an element in an array...
my_array.indexOf("find this value");
Is indexOf a lot better than storing how many elements are in an array, and looping through the array until you find the element you want? I could have simplified my code alot.
I tried to make my lookups constant time by using multiple arrays, and storing the keys. It makes insertions/deletes slow because I have to update the keys though.
Should I have just used indexOf?
Thanks
The vast majority of the time you are much better off to use a native function that has been optimized over whatever solution you come up with. Aside from that, however, you said something about storing the amount of elements in the array. Not sure why you did that when arrays have a .length property.
Javascript basically has two types of collections: Arrays and hashmaps. Both are a bit special. The hash map is just an object with named properties. The keys are strings that you use to access the values directly. Here's an example:
// create the hash map
var hashMap = {};
// add a value
var key = "John Dillinger";
hashMap[key] = "Criminal";
// retrieve the value
var stuff = hashMap[key];
Javascript arrays have a double functionality. They are of course arrays, but are also stacks. A stack follows the "last in - first out" rule. Here's an example of an array and a stack:
// Array example
var anArray = []; // or: var anArray = new Array();
anArray[0] = "some value";
alert(anArray[0]); // pops up "some value"
// Stack example
var stack = [];
stack.push("first");
stack.push("second");
alert(stack.pop()); // pop up "second"
Finally, for some problems a linked list could come in handy. For that you use an object. Something like this:
var linkedList = {value: "stuff"};
linkedList.next = {value: "other"};
linkedList.next.next = {value: "yet another value"};
// Traverse the list
var node = linkedList;
while(node) {
alert(node.value)
node = node.next;
}
Given the problem that you describe, I would use a hash map. Just remember to choose the correct collection type for any given problem.
You could use a hash table implementation in javascript to map values to array indices.
Native functions should be faster since it would be the runtime-engine precompiled code.
However, indexOf wasn't implemented until version 1.6, meaning it doesn't work in jscript/IE afaik.
But I would just prototype a workaround for it in that case. native functions is usually your best option.
In your case however, it seems that you want a hashmap, which in js is just a regular object as Helgi pointed out.
It's probable that the implementation of the indexOf method just loops over the array until it finds the requested value because in the general case that's about all you can do. Using it would clean up your code but is unlikely to make it faster. (There are faster ways of searching arrays but they carry certain restrictions and/or up-front costs.)
You should use the right data structure for the job. Arrays are for situations where order is important. If you find yourself searching through them a lot you should probably be using a hash instead. Hashes are unordered but lookups happen in constant time (no searching).
I've implemented javascript HashMap which code can be obtained from http://github.com/lambder/HashMapJS/tree/master
Here is the code:
/*
=====================================================================
#license MIT
#author Lambder
#copyright 2009 Lambder.
#end
=====================================================================
*/
var HashMap = function() {
this.initialize();
}
HashMap.prototype = {
hashkey_prefix: "<#HashMapHashkeyPerfix>",
hashcode_field: "<#HashMapHashkeyPerfix>",
initialize: function() {
this.backing_hash = {};
this.code = 0;
},
/*
maps value to key returning previous assocciation
*/
put: function(key, value) {
var prev;
if (key && value) {
var hashCode = key[this.hashcode_field];
if (hashCode) {
prev = this.backing_hash[hashCode];
} else {
this.code += 1;
hashCode = this.hashkey_prefix + this.code;
key[this.hashcode_field] = hashCode;
}
this.backing_hash[hashCode] = value;
}
return prev;
},
/*
returns value associated with given key
*/
get: function(key) {
var value;
if (key) {
var hashCode = key[this.hashcode_field];
if (hashCode) {
value = this.backing_hash[hashCode];
}
}
return value;
},
/*
deletes association by given key.
Returns true if the assocciation existed, false otherwise
*/
del: function(key) {
var success = false;
if (key) {
var hashCode = key[this.hashcode_field];
if (hashCode) {
var prev = this.backing_hash[hashCode];
this.backing_hash[hashCode] = undefined;
if(prev !== undefined)
success = true;
}
}
return success;
}
}
//// Usage
// creation
var my_map = new HashMap();
// insertion
var a_key = {};
var a_value = {struct: "structA"};
var b_key = {};
var b_value = {struct: "structB"};
var c_key = {};
var c_value = {struct: "structC"};
my_map.put(a_key, a_value);
my_map.put(b_key, b_value);
var prev_b = my_map.put(b_key, c_value);
// retrieval
if(my_map.get(a_key) !== a_value){
throw("fail1")
}
if(my_map.get(b_key) !== c_value){
throw("fail2")
}
if(prev_b !== b_value){
throw("fail3")
}
// deletion
var a_existed = my_map.del(a_key);
var c_existed = my_map.del(c_key);
var a2_existed = my_map.del(a_key);
if(a_existed !== true){
throw("fail4")
}
if(c_existed !== false){
throw("fail5")
}
if(a2_existed !== false){
throw("fail6")
}
Bon Appétit,
Lambder

Categories

Resources