w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Removing Multiple Objects from Javascript Array Breaks Half Way Through
Because the length of collection will change, the trick is to loop from rear to front for (var index = self.collection.length - 1; index >= 0; index--) { k = self.collection[index]; if (fbContactIDs.indexOf(k.id) > -1) { self.collection.splice(index, 1); }; }

Categories : Javascript

Build immutable NSDictionary from array with custom objects where each key could have multiple objects
There's no built-in concept of a one-to-many dictionary so I don't think there's a neater way to achieve exactly what you write — there's certainly no single line of syntax like there is for a whole bunch of other common manipulations. That said, minor suggestions would be: Use key-value coding to read the keyed property. So replace your references to obj.key with a single call to [obj valueForKeyPath:keyPath] and take keyPath as a parameter. Then you've got to write this code only once. For safety you should check that obj.key isn't nil. If it is then you'll end up doing [tmpMutableDic setObject:... forKey:nil], which raises an exception because dictionaries can't store values against a nil key. copy will return an immutable dictionary but the values in it will still be mutable arra

Categories : IOS

PHP Manipulating array values from multiple arrays into single array
Derp. I totally misread. And in the time it took me to fix it other people answered, but oh well. Here it is :) $items = array(); foreach($description AS $k=>$v){ if(isset($account[$k])){ $items[$k] = array($v, $account[$k]); // assuming you don't really want a comma sep string, but another array. } }

Categories : PHP

Shuffle multiple javascript arrays in the same way
From that example, simply add a second parameter (your second array) and perform the operation on both arrays. You will just need to add and use a second temp, so you aren't overwriting your temps. This should do the trick ASSUMING THE ARRAYS ARE THE SAME LENGTH: function shuffle(array, array2) { var counter = array.length, temp, temp2, index; // While there are elements in the array while (counter > 0) { // Pick a random index index = Math.floor(Math.random() * counter); // Decrease counter by 1 counter--; // And swap the last element with it temp = array[counter]; temp2 = array2[counter]; array[counter] = array[index]; array2[counter] = array2[index]; array[index] = temp; array2[

Categories : Javascript

How could I implement multiple dimensional arrays like this in Javascript?
If you want that exact syntax (with parens), MatrixVar would have to be a function in JavaScript. But it can't be a function, because you would be assigning to whatever the function returns. Multi-dimensional arrays look like arr[a][b][c][c][i], and are in fact nested arrays: var arr = []; for(var i=0; i<3; i++) { // create new nested arrays arr[i] = []; for(var j=0; j<3; j++) { // populate nested arrays arr[i][j] = j; } } At the end, arr will look like this: [ [0,1,2], [0,1,2], [0,1,2] ]

Categories : Javascript

posting multiple arrays to .net webservice using JavaScript
Make sure two things: Your json string is valid Json string name matches with property name on pagemethod In addition I would suggest you to go through below link which explains how to pass complex type to WebMethod. http://encosia.com/using-complex-types-to-make-calling-services-less-complex/

Categories : Javascript

Creating master array from multiple arrays
Best thing i came up with is this: for($i=0; $i<5; $i++){ $t = $i; $t1 = $t+3; $te= $i+5; $ti = $i+10; $a[] = array( 'date' => $t, 'bannana' => $te, 'tea' => $ti, ); $b[] = array( 'date' => $t1, 'lemon' => $te, ); $ar1[]=$a; $ar2[]=$b; } foreach($a as $key=>$value){ foreach($value as $k=>$v){ $ar[$value['date']][$k]=$v; } } foreach($b as $key=>$value){ foreach($value as $k=>$v){ $ar[$value['date']][$k]=$v; } } echo var_dump($ar); Where $a and $b are the 2 arrays and the field they are ordered by is 'date'. I looked in stack overflow

Categories : PHP

Putting multiple arrays from GetValueNames() into one array in C#
You don't need multiple arrays. Using a dictionary could be better. For ex; RegistryKey regKey = Registry.CurrentUser; var console = regKey.OpenSubKey("Console"); var dict = console.GetValueNames() .ToDictionary(key => key, key => console.GetValue(key)); foreach (var kv in dict) { Console.WriteLine(kv.Key + "=" + kv.Value); }

Categories : C#

File array returns multiple arrays
When you upload an array of files the array returned is a little strange in it's structure, not the most intuitive in my opinion. My solution is to use a for loop and not a foreach My HTML: <input type="file" name="image_name[]" /> <input type="file" name="image_name[]" /> <input type="file" name="image_name[]" /> My PHP: <?php $count = count($_FILES['image_name']['error']); for ($i = 0; $i < $count; $i++) { // image handling code here if ($_FILES['image_name']['error'][$i] == 0) { move_uploaded_file($_FILES['image_name']['tmp_name'][$i], 'whatever.jpg'); } }

Categories : PHP

Checking if each element of array is in multiple arrays
This looks like a job for a recursion (might not be the most efficient but definitely the easiest solution and if your data is this small it shouldn't matter): var check = function(input, colors) { if (!input.length) { return true; } var input_color = input.pop(); var ok = false; for (var i = 0; i < colors.length; i++) { var color = colors[i]; if (!color) { break; } if (color.indexOf(input_color) !== -1) { colors.splice(i, 1); ok = check(input, colors); if (!ok) { colors.splice(i, 0, color); } else { break; } } } if (!ok) { input.push(input_color); } return ok; }; and the usage: var colors

Categories : Javascript

pass multiple arrays and values into javascript function
Well, you could use the toString Javascript function http://www.w3schools.com/jsref/jsref_tostring_array.asp

Categories : Javascript

Putting array containing multiple arrays into mysql table
if you just want to store the array as object and dont want to run sql queries on it than serialize the object and save it as binary mysql. serialization: http://php.net/manual/de/arrayobject.serialize.php mysql-binary: http://dev.mysql.com/doc/refman/5.1/de/binary-varbinary.html

Categories : PHP

how to have one array as key and other multiple arrays as values in hashmap perl?
Loop over each index of the first array and push what you want into the destination. Note that the values of %hash need to be list-refs. $ cat ./foo.pl #! /usr/bin/perl use strict; use warnings; use Data::Dumper; my @array1 = ( "a", "b", "c" ); my @array2 = ( 1, 2, 3 ); my @array3 = ( "j", "k", "l" ); my %hash; for( my $i = 0; $i < scalar(@array1); $i++ ){ push( @{$hash{$array1[$i]}}, $array2[$i], $array3[$i] ); } print Dumper( \%hash ); $ ./foo.pl $VAR1 = { 'c' => [ 3, 'l' ], 'a' => [ 1, 'j' ], 'b' => [ 2, 'k' ] }; Note, for future reference, that it's importan

Categories : Arrays

Fastest/Easiest way to store multiple arrays of data for multiple time steps
Why not index via the particle id?: particles = struct; particles(id).t % length(t)-by-1 particles(id).x % length(t)-by-1 particles(id).y % length(t)-by-1 particles(id).xdot % length(t)-by-1 particles(id).ydot % length(t)-by-1 Then particles(id).x is a vector where each element corresponds to an element in particles(id).t. particles(1).x(1) would be the first x value for id 1. However, the problem with breaking things up with an id is that you won't be able to search across particles. I'd really just use arrays (or a struct containing arrays for all particles): particles = struct; particles.ids % 1-by-length(ids) particles.t % length(t)-by-1 or length(t)-by-length(ids) particles.x % length(t)-by-length(ids) particles.y % length(t)-by-length(ids) particles.xdot % leng

Categories : Arrays

Unable to add multiple String arrays into array using apache commons ArrayUtils
ArrayUtils.addAll(Object[] array1, Object[] array2) takes only two arguments and returns new array contains all of the element of array1 followed by all of the elements array2.

Categories : Java

Fastest way to reorder a numpy array across multiple axes using index arrays
Here is one way of doing this: def unscramble(A_shuf,ind_shuf): order = np.lexsort(ind_shuf[::-1]) return A_shuf.flat[order].reshape(A_shuf.shape) You essentially have the rank of each item in the form of n indices, ie a = (0, 0), b = (0, 1), c = (0, 2), d = (1, 0) ... and so on. If you argsort the ranks you'll the the reordering you need to put the items in ascending order. You could use lexsort or you could use numpy.ravel_multi_index to get the ranks as integers and apply the argsort on the integer ranks. Let me know if the explanation isn't clear.

Categories : Python

Access multiple items in multiple arrays from JSON using AngularJS
You are trying to set $scope.employees to data, when it should be data.entries 'use strict'; function EmpListCtrl($scope, $http) { $http.get('employees.json').success(function(data) { $scope.employees = data.entries; }); } Then you need to reference employee.phone instead of phone: <div ng-app> <div ng-controller="EmpListCtrl"> <h1>Employees</h1> <ul> <li ng-repeat="employee in employees"> {{employee.lastName}}, {{employee.firstName}}<br/> <a href="mailto:{{employee.email}}">{{employee.email}}</a> <ul> <li ng-repeat="num in employee.phone"> {{num.area}}-{{num.number}}-{{num.extn}}

Categories : Json

Removing multiple input names on output formdata strings/arrays with Javascript
You'll want to be careful with that code, unless you don't expect user-generated input, as you may end up replacing something that you didn't want to. There are a few JS libraries that will pull out the submitted values for you in a much safer way that you may want to research. The issue that you're encountering is that it will only replace "=on" as many times as it replaces "+" with " ". If you add an additional while-loop, you can replace "=on" until they're all gone. while (formData.indexOf("+") != -1) { formData = formData.replace("+", " "); } while (formData.indexOf("=on") != -1) { formData = formData.replace("=on", ""); }

Categories : Javascript

Sort Objects in Array by Multiple Properties
You need to reassign the parsed value back to a and b: a = parseFloat(a); b = parseFloat(b); Otherwise it ends up comparing strings, and 12 occurs after 1 lexically, just like the word at comes after a in the dictionary. Updated fiddle.

Categories : Javascript

Instantiate multiple objects in a non-mutable array
NSMutableArray is a subclass of NSArray, so this will work just fine: return _temporaryArray; (I would avoid the _ prefix, however, as that is commonly used to signify instance variables, not auto variables). This seems to fit your criteria: focus on performance: no need to make a copy. focus on memory consumption: no need to make a copy. focus on code brevity: no need to make a copy. Note, however, the caller could, in theory, cast your NSArray back to an NSMutableArray and start modifying the object, however there is only so much you should worry about.

Categories : Objective C

Sort an array of objects by multiple properties
Use comparator function from Array you can check answers here : Sorting objects in an array by a field value in JavaScript

Categories : Javascript

add objects in array from multiple array in iphone
Yes, you should use Dictionary instead of Array. Set the Array as an Object with the Key as ArrayName. Sample Code : NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithObjectsAndKeys:arrayA,@"ArrayA",arrayB,@"ArrayB", nil]; NSLog(@"dict :: %@",dict); Update : To display the title & id in the TableView cell : yourTitleLabel.text = [[[dict objectForKey:@"ArrayA"] objectAtIndex:indexPath.row] objectForKey:@"title"]; yourIdLabel.text = [[[dict objectForKey:@"ArrayA"] objectAtIndex:indexPath.row] objectForKey:@"id"];

Categories : Iphone

Simple way to get multiple related objects in Parse.com with Javascript?
I finally sorted this out, though there is a caveat that makes this work differently than the documentation would indicate. //Assuming we have 'player', an object of Class 'Player'. var r = player.relation("trophies"); r.query().find({ success: function(trophies){ response.success(trophies); //list of trophies pointed to by that player's "trophies" column. }, error: function(error){ response.error(error); } }) The caveat: You must have a 'full' player object in memory for this to work. You can't save a player object, grab the object from the success callback and have this work. Some reason, the object that is returned in the success handler is appears to be an incomplete Parse.Object, and is missing some of the methods required to do this. Another stumbling block abou

Categories : Javascript

Javascript Generalise Function for Multiple Objects (Raphael JS)
You can do this : var menuHoverIn = function(target) { target.animate({ "fill": "#128A8F" }, 500); }; var menuHoverOut = function(target) { target.animate({ "fill": "#010101" }, 500) }; something.hover( menuHoverIn, menuHoverOut ); Here is two good articles about object "and" functions : http://hangar.runway7.net/javascript/guide and http://jamesallardice.com/explaining-function-and-variable-hoisting-in-javascript/ To animate another object : // Function.prototype.bind polyfill if ( !Function.prototype.bind ) { Function.prototype.bind = function( obj ) { if(typeof this !== 'function') // closest thing possible to the ECMAScript 5 internal IsCallable function throw new TypeError('Function.prototype.bind - what is trying to be bound is not

Categories : Javascript

Select multiple custom objects on KineticJS and Javascript
You want to give your custom shapes a name like this: this.celestialBody = new Kinetic.Circle({ name: cb.name, // <-- This works like a CSS Class and can be selected with "." id: cb.id, x:cb.x, y:cb.y, fill:cb.color, radius:cb.radius, shadowColor: cb.glow, shadowBlur: cb.glowBlur, shadowOffset: 0, shadowOpacity: cb.glowOpacity }); In this case I would give your custom shapes a meaningful name that groups the shapes together, something like "asteroids" and add that inside your loop: for (var i = 0; i < 20;i++){ var asteroidID = 'asteroid' + i; var name = 'asteroids'; var asteroid = new addCelestial({name: name, color: 'rgb(255,255,255)',layer:layer0, id: asteroidID}); asteroid.radius(1); asteroid.xpos((Math.random()*300)+200); asteroid

Categories : Javascript

Get rails ActiveRecord instead of Array of objects for multiple queries
I am not sure I correcly undestood the problem, but I will try to help anyway. As especified here where returns an ActiveRecord::Relation find (and its related dynamic methods) returns a single model object So I suggest divide your queries into: 'joins' and 'where' fields. Your new code should look like something like this: pb << User.joins(q.query_joins).where(q.query_where) Also find methods will are deprecated in rails 4, so using where is recommended. Hope I haven't missed the point too much :-)

Categories : Mysql

How to access multiple json objects send in array django
While this is very old I found myself searching for this exact problem... I found a way that works although I feel it is a bit unreliable Javascript: var rows = []; $('.some_class').each(function(){ var id = $(this).attr('data-id'); var something = $(this).attr('data-something'); var item = {}; item["id"] = id; item["something"] = something; rows.push(JSON.stringify(item)); }); arr = rows.join("/"); ajax_req = $.ajax({ url: '../some_url/', type: "POST", data: {req_arr : arr}, }); views.py items = request.POST.get('req_arr', None) items = str(items).split("/") for i in range(0, len(items)): item = json.loads(items[i]) id = item['id'] something = item['something']

Categories : Javascript

Using IRepository pattern for multiple domain objects and multiple storage mechanisms
Please refer to How would I design a repository to handle multiple data access strategies? , I think this is what you want. Basically assume you already have one IRepository interface having methods of CRUD and other generic methods refer by all your other repository, then you have multi implementations to IRepository interface. After that use any IOC container (I use Windsor Castle) to resolve which implement's component should take part for this interface doing application setup.

Categories : C#

What would be the best way to go about writing this in JS/jQuery? (Multiple individual objects with multiple fields)
Honestly, with the amount of data you are talking about and the number of ways it could be modified, you should look into a framework that is more robust and was designed to make data binding much easier. There are many out there, but my personal favorite is AngularJS. http://angularjs.org/ Start looking into this as it may save you a lot of time in developing the app and then of course maintaining it down the road.

Categories : PHP

How to send an array of strings in JSON to create multiple objects in Rails?
Base64 is a red-herring (something that can confuse an argument) so let's put that aside for a minute. JSON is capable of representing an array, so that's the place to start, because you want two of something. Pretending that we're doing what JavaScript and the browser would do is easy: require 'json' ary = ['content for box one', 'content for box two'] puts JSON[ary] # >> ["content for box one","content for box two"] At this point we have the same sort of base string that JavaScript would create for an array containing two ASCII strings. For this part of the test, it's inconsequential whether it's ASCII or binary. Note that JSON left the content of the strings in the array alone. We can use the BASE64 encoding inside those strings and know that JSON will leave it alone: puts

Categories : Ruby On Rails

Django Populating multiple forms with multiple objects
You are looking for the formsets A formset is a layer of abstraction to work with multiple forms on the same page. It can be best compared to a data grid.

Categories : Django

Multiple SQL Queries Into Multiple Arrays
There is no restriction on number of queries executed during a script execution. There is however no reason that you couldn't get this information in a single query. You would use a JOIN to do this. This might look like this: SELECT bp.* FROM users AS u INNER JOIN blog_posts AS bp ON u.id = bp.poster_id WHERE u.username = '?' The particular problem you mention in comment to other answer is because you need to call mysql_free_result() before making your next query.

Categories : PHP

Using JQuery/JavaScript how would I group values in an array of objects and create a new array of objects from the groups
If you're willing to use Underscore.js, this becomes pretty trivial. Assuming data is your original list of json objects, this will achieve what you're after: var groups = []; var by_grade = _.groupBy(data, function(obj) { return obj['grade'] }); _.each(by_grade, function(objs, grade) { var group = {}; group['grade'] = grade; group['ids'] = _.pluck(objs, 'id'); group['versions'] = _.pluck(objs, 'version'); // Use the following if the value is known to be // the same for all grouped objects group['platform'] = objs[0]['platform']; // And the rest... groups.push(group); }); _.groupBy() will group your objects by grade, resulting in two objects with the keys X and A, whose values are lists of objects with the corresponding grades. You can then loop ove

Categories : Javascript

Objects in JavaScript arrays
You should Create new Cards something like this (using your existing method of passing in arrays when creating a card: function Card(suit,num,points) { var i = Math.floor(Math.random() * 13 ) this.suit = suit[i]; this.number = number[i]; this.points = points[i]; } Then when you want to create a card: var myCard = new Card(suits,numbers,points);

Categories : Javascript

match two arrays or objects in javascript
You may do it this way: $.each(categorization,function(id, val){ var tempObj = {}; tempObj[val] = category[val]; combinedResult[id] = tempObj; }); Here's sample Fiddle.

Categories : Javascript

Javascript D3.js Manipulating arrays of objects
There's unfortunately no join operator or equivalent in Javascript -- you have to explicitly search for the matches. In your case, you can do this with a nested loop. The code would look something like this. var results = []; for(var i = 0; i < statedataset.length; i++) { if(statedataset[i].State == "SD" || statedataset[i].State == "MN" || statedataset[i].State == "IA") { var j = 0; for(j = 0; j < nationaldataset.length; j++) { if(nationaldataset[j].nanswer == statedataset[i].columnname) { break; } } if(j < nationaldataset.length) { results.push({ "nquestion": nationaldataset[j].nquestion, "nanswer": nationaldataset[j].nanswer, "nscore": nationaldataset[j].nscore, "Score": statedataset[i].Score

Categories : Javascript

Merge objects in arrays in Javascript
This should do what you want: var merge = function(t1, t2) { var arr = []; for(i=0; i<t1.length; i++) { for(var prop in t2[i]) { arr.push(t1[i]); arr[i][prop] = t2[i][prop]; } } return arr; } var tab3 = merge(tab1, tab2);

Categories : Javascript

Random objects from Arrays in Javascript
var num = new Array('1','2','3','4','5','6','7','6'); That's an array of string literals that contain numbers. var num = new Array(1,2,3,4,5,6,7,6); That's an array of number literals. var colors= new Array('red','blue','green','orange','cyan','yellow', 'black'); That's an array of string literals. var colors= new Array(red,blue,green,orange,cyan,yellow, black); That's an array of variables. The numbers will be automatically stringified when concatenated with the " : " string and therefore work like number strings, but your variables will just throw Undefined Variable exceptions.

Categories : Javascript

merge two javascript objects that contain arrays
Array.prototype.unique = function() { var a = this.concat(); for(var i=0; i<a.length; ++i) { for(var j=i+1; j<a.length; ++j) { if(a[i] === a[j]) a.splice(j--, 1); } } return a; }; var mergedArray = array1.concat(array2).unique(); via this question - How to merge two arrays in Javascript

Categories : Javascript

Javascript show multiple table rows from multiple select
I have fixed the problem myself, the solution was: $('table#newspaper-a tr:not(#header, #trWeekNummer)').hide(); if(List[x].selected) { $('table#newspaper-a tr:not(#header, #trWeekNummer)').each(function(){ $('td:nth-child(1)',this).each(function(){ if($(this).text() == List[x].value) $(this).parent(this).show(); }); }); }

Categories : Javascript



© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.