How do you add an array to another array in Ruby and not end up with a multi-dimensional result?

You’ve got a workable idea, but the #flatten! is in the wrong place — it flattens its receiver, so you could use it to turn [1, 2, [‘foo’, ‘bar’]] into [1,2,’foo’,’bar’]. I’m doubtless forgetting some approaches, but you can concatenate: a1.concat a2 a1 + a2 # creates a new array, as does a1 += a2 … Read more

How to sort an array of associative arrays by value of a given key in PHP?

You are right, the function you’re looking for is array_multisort(). Here’s an example taken straight from the manual and adapted to your case: $price = array(); foreach ($inventory as $key => $row) { $price[$key] = $row[‘price’]; } array_multisort($price, SORT_DESC, $inventory); As of PHP 5.5.0 you can use array_column() instead of that foreach: $price = array_column($inventory, … Read more

How to convert Java String into byte[]?

The object your method decompressGZIP() needs is a byte[]. So the basic, technical answer to the question you have asked is: byte[] b = string.getBytes(); byte[] b = string.getBytes(Charset.forName(“UTF-8”)); byte[] b = string.getBytes(StandardCharsets.UTF_8); // Java 7+ only However the problem you appear to be wrestling with is that this doesn’t display very well. Calling toString() … Read more

Most efficient way to convert an HTMLCollection to an Array

var arr = Array.prototype.slice.call( htmlCollection ) will have the same effect using “native” code. Edit Since this gets a lot of views, note (per @oriol’s comment) that the following more concise expression is effectively equivalent: var arr = [].slice.call(htmlCollection); But note per @JussiR’s comment, that unlike the “verbose” form, it does create an empty, unused, … Read more

Find a value in an array of objects in Javascript [duplicate]

Finding the array element: let arr = [ { name:”string 1″, value:”this”, other: “that” }, { name:”string 2″, value:”this”, other: “that” } ]; let obj = arr.find(o => o.name === ‘string 1’); console.log(obj); Replacing the array element: let arr = [ { name:”string 1″, value:”this”, other: “that” }, { name:”string 2″, value:”this”, other: “that” } … Read more

Insert new item in array on any position in PHP

You may find this a little more intuitive. It only requires one function call to array_splice: $original = array( ‘a’, ‘b’, ‘c’, ‘d’, ‘e’ ); $inserted = array( ‘x’ ); // not necessarily an array, see manual quote array_splice( $original, 3, 0, $inserted ); // splice in at position 3 // $original is now a … Read more

How do I declare an array in Python?

variable = [] Now variable refers to an empty list*. Of course this is an assignment, not a declaration. There’s no way to say in Python “this variable should never refer to anything other than a list”, since Python is dynamically typed. *The default built-in Python type is called a list, not an array. It … Read more