How do you get the first element from an array like this:
var ary = ['first', 'second', 'third', 'fourth', 'fifth'];
I tried this:
alert($(ary).first());
But it would return [object Object]. So I need to get the first element from the array which should be the element 'first'.
like this
alert(ary[0])
Why are you jQuery-ifying a vanilla JavaScript array? Use standard JavaScript!
var ary = ['first', 'second', 'third', 'fourth', 'fifth'];
alert(ary[0]);
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array
Also,
Source, courtesy of bobince
Some of ways below for different circumstances.
In most normal cases, the simplest way to access the first element is by
yourArray[0]
but this requires you to check if [0] actually exists.
Another commonly used method is shift() but you should avoid using this for the purpose of accessing the first element.
Well, this method modifies the original array (removes the first item and returns it) but re-indexes what is left in the array to make it start from 0 (shifts everything down). Therefore the length of an array is reduced by one.
There are good cases where you may need this, for example, to take the first customer waiting in the queue, but it is very inefficient to use this for the purpose of accessing the first element.
In addition, this requires a perfect array with [0] index pointer intact, exactly as using [0];
yourArray.shift()
The important thing to know is that the two above are only an option if your array starts with a [0] index.
There are cases where the first element has been deleted, for example with delete yourArray[0], leaving your array with "holes". Now the element at [0] is simply undefined, but you want to get the first "existing" element. I have seen many real world cases of this.
So, assuming we have no knowledge of the array and the first key (or we know there are holes), we can still get the first element.
You can use find() to get the first element.
The advantage of find() is its efficiency as it exits the loop when the first value satisfying the condition is reached (more about this below).
(You can customize the condition to exclude null or other empty values too)
var firstItem = yourArray.find(x=>x!==undefined);
I'd also like to include filter() here as an option to first "fix" the array in the copy and then get the first element while keeping the original array intact (unmodified).
Another reason to include filter() here is that it existed before find() and many programmers have already been using it (it is ES5 against find() being ES6).
var firstItem = yourArray.filter(x => typeof x!==undefined).shift();
Warning that filter() is not really an efficient way (filter() runs through all elements) and creates another array. It is fine to use on small arrays as performance impact would be marginal, closer to using forEach(), for example.
Another one I have seen in some projects is splice() to get the first item in an array and then get it by index:
var firstItem = yourArray.splice(0, 1)[0];
I am not sure why you would do that. This method won't solve the problem with holes in an array (sparse array). It is costly as it will re-index the array, and it returns an array that you have to access again to get the value. For example, if you delete the first couple of elements, then splice() will return undefined instead of the first defined value from the array.
Both find() and filter() guarantee the order of elements, so are safe to use as above.
**(I see some people suggest using loops to get the first element, but I would recommend against this method. Obviously, you can use any loop to get a value from an array but why would you do that?
Readability, optimization, unnecessary block of code etc. When using native functions, the browser can better optimize your code. And it may not even work with some loops which don't guarantee the order in iteration.
By the way, forEach() doesn't solve the issue as many suggest because you can't break it and it will run through all elements. You would be better off using a simple for loop and by checking key/value, but why?**
Using ES6 destructuring
let [first] = [1,2,3];
Which is the same as
let first = [1,2,3][0];
You can just use find():
const first = array.find(Boolean)
Or if you want the first element even if it is falsy:
const first = array.find(() => true)
Or if you want the first element even if it is falsy but not if it is null or undefined (more information):
const first = array.find(e => typeof e !== 'undefined')
Going the extra mile:
If you care about readability but don't want to rely on numeric incidences you could add a first()-function to Array.prototype by defining it with Object.defineProperty() which mitigates the pitfalls of modifying the built-in Array object prototype directly (explained here).
Performance is pretty good (find() stops after the first element) but it isn't perfect or universally accessible (ES6 only). For more background read #Selays answer.
Object.defineProperty(Array.prototype, 'first', {
value() {
return this.find(e => true) // or this.find(Boolean)
}
})
To retrieve the first element you are now able to do this:
const array = ['a', 'b', 'c']
array.first()
> 'a'
Snippet to see it in action:
Object.defineProperty(Array.prototype, 'first', {
value() {
return this.find(Boolean)
}
})
console.log( ['a', 'b', 'c'].first() )
Element of index 0 may not exist if the first element has been deleted:
let a = ['a', 'b', 'c'];
delete a[0];
for (let i in a) {
console.log(i + ' ' + a[i]);
}
Better way to get the first element without jQuery:
function first(p) {
for (let i in p) return p[i];
}
console.log( first(['a', 'b', 'c']) );
If you want to preserve the readibility you could always add a first function to the Array.protoype:
Array.prototype.first = function () {
return this[0];
};
A then you could easily retrieve the first element:
[1, 2, 3].first();
> 1
If your array is not guaranteed to be populated from index zero, you can use Array.prototype.find():
var elements = []
elements[1] = 'foo'
elements[2] = 'bar'
var first = function(element) { return !!element }
var gotcha = elements.find(first)
console.log(a[0]) // undefined
console.log(gotcha) // 'foo'
array.find(e => !!e); // return the first element
since "find" return the first element that matches the filter && !!e match any element.
Note This works only when the first element is not a "Falsy" : null, false, NaN, "", 0, undefined
In ES2015 and above, using array destructuring:
const arr = [42, 555, 666, 777]
const [first] = arr
console.log(first)
Only in case you are using underscore.js (http://underscorejs.org/) you can do:
_.first(your_array);
I know that people which come from other languages to JavaScript, looking for something like head() or first() to get the first element of an array, but how you can do that?
Imagine you have the array below:
const arr = [1, 2, 3, 4, 5];
In JavaScript, you can simply do:
const first = arr[0];
or a neater, newer way is:
const [first] = arr;
But you can also simply write a function like...
function first(arr) {
if(!Array.isArray(arr)) return;
return arr[0];
}
If using underscore, there are list of functions doing the same thing you looking for:
_.first
_.head
_.take
ES6 Spread operator + .shift() solution
Using myArray.shift() you can get the 1st element of the array, but .shift() will modify the original array, so to avoid this, first you can create a copy of the array with [...myArray] and then apply the .shift() to this copy:
var myArray = ['first', 'second', 'third', 'fourth', 'fifth'];
var first = [...myArray].shift();
console.log(first);
Try alert(ary[0]);.
I prefer to use Array Destructuring
const [first, second, third] = ["Laide", "Gabriel", "Jets"];
console.log(first); // Output: Laide
console.log(second); // Output: Gabriel
console.log(third); // Output: Jets
Method that works with arrays, and it works with objects too (beware, objects don't have a guaranteed order!).
I prefer this method the most, because original array is not modified.
// In case of array
var arr = [];
arr[3] = 'first';
arr[7] = 'last';
var firstElement;
for(var i in arr){
firstElement = arr[i];
break;
}
console.log(firstElement); // "first"
// In case of object
var obj = {
first: 'first',
last: 'last',
};
var firstElement;
for(var i in obj){
firstElement = obj[i];
break;
}
console.log(firstElement) // First;
Just use ary.slice(0,1).pop();
In
var ary = ['first', 'second', 'third', 'fourth', 'fifth'];
console.log("1º "+ary.slice(0,1).pop());
console.log("2º "+ary.slice(0,2).pop());
console.log("3º "+ary.slice(0,3).pop());
console.log("4º "+ary.slice(0,4).pop());
console.log("5º "+ary.slice(0,5).pop());
console.log("Last "+ary.slice(-1).pop());
array.slice(START,END).pop();
Another one for those only concerned with truthy elements
ary.find(Boolean);
Find the first element in an array using a filter:
In typescript:
function first<T>(arr: T[], filter: (v: T) => boolean): T {
let result: T;
return arr.some(v => { result = v; return filter(v); }) ? result : undefined;
}
In plain javascript:
function first(arr, filter) {
var result;
return arr.some(function (v) { result = v; return filter(v); }) ? result : undefined;
}
And similarly, indexOf:
In typescript:
function indexOf<T>(arr: T[], filter: (v: T) => boolean): number {
let result: number;
return arr.some((v, i) => { result = i; return filter(v); }) ? result : undefined;
}
In plain javascript:
function indexOf(arr, filter) {
var result;
return arr.some(function (v, i) { result = i; return filter(v); }) ? result : undefined;
}
Why not account for times your array might be empty?
var ary = ['first', 'second', 'third', 'fourth', 'fifth'];
first = (array) => array.length ? array[0] : 'no items';
first(ary)
// output: first
var ary = [];
first(ary)
// output: no items
When there are multiple matches, JQuery's .first() is used for fetching the first DOM element that matched the css selector given to jquery.
You don't need jQuery to manipulate javascript arrays.
You could also use .get(0):
alert($(ary).first().get(0));
To get the first element of the array.
Declare a prototype to get first array element as:
Array.prototype.first = function () {
return this[0];
};
Then use it as:
var array = [0, 1, 2, 3];
var first = array.first();
var _first = [0, 1, 2, 3].first();
Or simply (:
first = array[0];
The previous examples work well when the array index begins at zero. thomax's answer did not rely on the index starting at zero, but relied on Array.prototype.find to which I did not have access. The following solution using jQuery $.each worked well in my case.
let haystack = {100: 'first', 150: 'second'},
found = null;
$.each(haystack, function( index, value ) {
found = value; // Save the first array element for later.
return false; // Immediately stop the $.each loop after the first array element.
});
console.log(found); // Prints 'first'.
try
var array= ['first', 'second', 'third', 'fourth', 'fifth'];
firstElement = array[array.length - array.length];
https://playcode.io/908187
A vanilla JS code, no jQuery, no libs, no-nothing.. :P.. It will work if array index does not start at zero as well.
var ary = ['first', 'second', 'third', 'fourth', 'fifth'];
console.log(Object.values(ary)[0]);
If you're chaining a view functions to the array e.g.
array.map(i => i+1).filter(i => i > 3)
And want the first element after these functions you can simply add a .shift() it doesn't modify the original array, its a nicer way then array.map(i => i+1).filter(=> i > 3)[0]
If you want the first element of an array without modifying the original you can use array[0] or array.map(n=>n).shift() (without the map you will modify the original. In this case btw i would suggest the ..[0] version.
var ary = ['first', 'second', 'third', 'fourth', 'fifth'];
console.log(Object.keys(ary)[0]);
Make any Object array (req), then simply do Object.keys(req)[0] to pick the first key in the Object array.
var ary = ["first", "second", "third", "fourth", "fifth"];
console.log(ary.shift());
//first
cosnole.log(ary);
// ["second", "third", "fourth", "fifth"]
#NicoLwk You should remove elements with splice, that will shift your array back. So:
var a=['a','b','c'];
a.splice(0,1);
for(var i in a){console.log(i+' '+a[i]);}
I'm trying to target JMS servers in the cloud, the puppet module init.pp needs to add a key to a hash.
I'm reading a block of hiera and having to extract parts of it to form a new hash. .each doesn't return any values so I'm using .map.
The values I'm getting out are exactly as I want, however when I tried a deep_merge I discovered that .map outputs as an array.
service.yaml
jms_subdeployment_instances:
'BPMJMSModuleUDDs:BPMJMSSubDM':
ensure: 'present'
target:
- 'BPMJMSServer_auto_1'
- "BPMJMSServer_auto_%{::ec2_tag_name}"
targettype:
- 'JMSServer'
- 'JMSServer'
init.pp
$jms_subdeployments = lookup('jms_subdeployment_instances', $default_params)
$jms_target_args = $jms_subdeployments.map |$subdep, $value| {
$jms_short_name = $subdep[0, 3]
$jms_subdeployment_inst = $array_domain_jmsserver_addresses.map |$index, $server| {
"${jms_short_name}JMSServer_auto_${server}"
if defined('$jms_subdeployment_inst') {
$jmsTargetArg = {
"${subdep}" => {
'target' => $jms_subdeployment_inst
}
}
}
}
$merge_subdeployment_targets = merge($jms_subdeployments, $jms_target_args)
```Output
New JMS targets are : [{BPMJMSModuleUDDs:BPMJMSSubDM => {target => [BPMJMSServer_auto_server101, BPMJMSServer_auto_server102]}}]
The enclosing [ ] are causing me trouble. As far as I can see, in puppet .to_h doesn't work either
Thanks
Update 22/07/2019:
Thanks for the reply, I've had to tweak it slightly because puppet was failing with "Server Error: Evaluation Error: Error while evaluating a Method call, 'values' parameter 'hsh' expects a Hash value, got Tuple"
$array_domain_jmsserver_addresses =
any2array(hiera('pdb_domain_msserver_addresses'))
$array_domain_jmsserver_addresses.sort()
$jms_subdeployments = lookup('jms_subdeployment_instances', $default_params)
$hash_domain_jmsserver_addresses = Hash($array_domain_jmsserver_addresses)
if $hash_domain_jmsserver_addresses.length > 0 {
$jms_target_arg_tuples = $jms_subdeployments.keys.map |$subdep| {
$jms_short_name = $subdep[0, 3]
$jms_subdeployment_inst = regsubst(
$hash_domain_jmsserver_addresses.values, /^/, "${jms_short_name}JMSServer_auto_")
# the (key, value) tuple to which this element maps
[ $subdep, { 'target' => $jms_subdeployment_inst } ]
}
$jms_target_args = Hash($jms_target_arg_tuples)
} else {
$jms_target_args = {}
}
notify{"Normal array is : ${jms_subdeployments}": }
notify{"Second array is : ${jms_target_args}": }
$merge_subdeployment_targets = deep_merge($jms_subdeployments, $jms_target_args)
notify{"Merged array is : ${merge_subdeployment_targets}": }
Normal is : {BPMJMSModuleUDDs:BPMJMSSubDM => {ensure => present, target => [BPMJMSServer_auto_1, BPMJMSServer_auto_server1], targettype => [JMSServer, JMSServer]},
Second is : {BPMJMSModuleUDDs:BPMJMSSubDM => {target => [BPMJMSServer_auto_server2]}
Merged is : {BPMJMSModuleUDDs:BPMJMSSubDM => {ensure => present, target => [BPMJMSServer_auto_server2], targettype => [JMSServer, JMSServer]}
Desired output it:
{BPMJMSModuleUDDs:BPMJMSSubDM => {ensure => present, target => [BPMJMSServer_auto_1, BPMJMSServer_auto_server1, BPMJMSServer_auto_server2], targettype => [JMSServer, JMSServer, JMSServer]}
when I tried a deep_merge I discovered that .map outputs as an array.
Yes, this is its documented behavior. map() should be considered a function on the elements of a collection, not on the collection overall, and the results are always provided as an array.
It would probably be useful to look over the alternatives for converting values to hashes. Particularly attractive is this one:
An Array matching Array[Tuple[Any,Any], 1] is converted to a hash where each tuple describes a key/value entry
To make use of this, map each entry to a (key, value) tuple, and convert the resulting array of tuples to a hash. A conversion of your attempt to that approach might look something like this:
if $array_domain_jmsserver_addresses.length > 0 {
$jms_target_arg_tuples = $jms_subdeployments.keys.map |$subdep| {
$jms_short_name = $subdep[0, 3]
$jms_subdeployment_inst = regsubst(
$array_domain_jmsserver_addresses.sort, /^/, "${jms_short_name}JMSServer_auto_")
# the (key, value) tuple to which this element maps
[ $subdep, { 'target' => $jms_subdeployment_inst } ]
}
$jms_target_args = Hash($jms_target_arg_tuples)
} else {
$jms_target_args = {}
}
$merge_subdeployment_targets = merge($jms_subdeployments, $jms_target_args)
Note that since you don't use the values of $jms_subdeployments, I have taken the liberty of simplifying your code somewhat by applying the keys() function to it. I have also used regsubst() instead of map() to form target names from the elements of $array_domain_jmsserver_addresses, which I personally find more readable in this case, especially since you were not using the indexes.
I've also inferred what I think you meant your if defined() test to accomplish, and replaced it with the outermost test of the length of the $array_domain_jmsserver_addresses array. One could also write it in somewhat more functional form, by building the hash without regard to whether there are any targets, and then filter()ing it after, but that seems wasteful because it appears that either all entries will have (the same) targets, or none will.
I've distilled this down to as few lines of code as I could to get to the bottom of this issue.
currently these are the config constants below (I'm using a array of length 1 to represent tokenised words I'm doing semantic analysis on.
export const top_words = 10000;
export const max_review_length = 1
export const embedding_vector_length = 32
Here is the code, I've substituted the tensors with mock tokens or one word length for now. I'm getting typescript linting errors showing that .print() or .dataSync()[0] will fail on the basis that they do not exist. the line of code in question (.predict) is returning a tensor which has no print or datasync method
const x_train = tf.tensor([[80], [86], [10], [1], [2]]);
const y_train = tf.tensor([[1],[1],[1],[0],[0]])
const x_val = tf.tensor([[1], [3], [102], [100], [104]]);
const y_val = tf.tensor([[0],[0],[1],[1],[1]])
const model = tf.sequential();
model.add(tf.layers.embedding({ inputDim: dictionary.size, inputLength: max_review_length, outputDim: 1 }))
model.add(tf.layers.lstm({units: 200, dropout: 0.2, recurrentDropout: 0.2}))
model.add(tf.layers.dense({units: 1, activation:'sigmoid'}))
model.compile({ loss:'binaryCrossentropy', optimizer:'rmsprop', metrics:['accuracy'] })
const history=model.fit(x_train, y_train,{epochs: 12, batchSize: 5})
history.then(hist => console.log(hist.history.loss)) // Show error loss vs epoch
const predictOut = model.predict(tf.tensor2d([10]))
predictOut.print() or predictOut.dataSync()[0]
returns
If you are using TypeScript you need to specify what predict() returns in such way:
(model.predict(...) as tf.Tensor).print()
since predict() can return either a Tensor or Tensor[]
Ok, so one thing thats easy to forget if you're not used to dealing with Python. Python is syncronous!
the model is async so to solve this problem in this code.
history (the result)
history.then(result => {
model.predict(tftensor2d([10)).print()
console.log('loss ', result.history.loss)
}
otherwise the model doesnt yet have a predict method as it is still calculating.
Gotta love async.