1586088420
In this JavaScript tutorial we’re going to learn about the indexOf and lastIndexOf JavaScript Array Methods and how they can be used in order to retrieve the index at which an item is found inside of an array.
If the element is not inside the array, the methods will return -1.
The **indexOf()**
method returns the first index at which a given element can be found in the array, or -1 if it is not present.
const beasts = ['ant', 'bison', 'camel', 'duck', 'bison'];
console.log(beasts.indexOf('bison'));
// expected output: 1
// start from index 2
console.log(beasts.indexOf('bison', 2));
// expected output: 4
console.log(beasts.indexOf('giraffe'));
// expected output: -1
arr.indexOf(searchElement[, fromIndex])
searchElement
Element to locate in the array.
fromIndex
| Optional
The index to start the search at. If the index is greater than or equal to the array’s length, -1 is returned, which means the array will not be searched. If the provided index value is a negative number, it is taken as the offset from the end of the array. Note: if the provided index is negative, the array is still searched from front to back. If the provided index is 0, then the whole array will be searched. Default: 0 (entire array is searched).
The first index of the element in the array; -1 if not found.
indexOf()
compares searchElement
to elements of the Array using strict equality (the same method used by the ===
or triple-equals operator).
indexOf()
The following example uses indexOf()
to locate values in an array.
var array = [2, 9, 9];
array.indexOf(2); // 0
array.indexOf(7); // -1
array.indexOf(9, 2); // 2
array.indexOf(2, -1); // -1
array.indexOf(2, -3); // 0
var indices = [];
var array = ['a', 'b', 'a', 'c', 'a', 'd'];
var element = 'a';
var idx = array.indexOf(element);
while (idx != -1) {
indices.push(idx);
idx = array.indexOf(element, idx + 1);
}
console.log(indices);
// [0, 2, 4]
function updateVegetablesCollection (veggies, veggie) {
if (veggies.indexOf(veggie) === -1) {
veggies.push(veggie);
console.log('New veggies collection is : ' + veggies);
} else if (veggies.indexOf(veggie) > -1) {
console.log(veggie + ' already exists in the veggies collection.');
}
}
var veggies = ['potato', 'tomato', 'chillies', 'green-pepper'];
updateVegetablesCollection(veggies, 'spinach');
// New veggies collection is : potato,tomato,chillies,green-pepper,spinach
updateVegetablesCollection(veggies, 'spinach');
// spinach already exists in the veggies collection.
indexOf()
was added to the ECMA-262 standard in the 5th edition; as such it may not be present in all browsers. You can work around this by utilizing the following code at the beginning of your scripts. This will allow you to use indexOf()
when there is still no native support. This algorithm matches the one specified in ECMA-262, 5th edition, assuming TypeError
and Math.abs()
have their original values.
// This version tries to optimize by only checking for "in" when looking for undefined and
// skipping the definitely fruitless NaN search. Other parts are merely cosmetic conciseness.
// Whether it is actually faster remains to be seen.
if (!Array.prototype.indexOf)
Array.prototype.indexOf = (function(Object, max, min) {
"use strict"
return function indexOf(member, fromIndex) {
if (this === null || this === undefined)
throw TypeError("Array.prototype.indexOf called on null or undefined")
var that = Object(this), Len = that.length >>> 0, i = min(fromIndex | 0, Len)
if (i < 0) i = max(0, Len + i)
else if (i >= Len) return -1
if (member === void 0) { // undefined
for (; i !== Len; ++i) if (that[i] === void 0 && i in that) return i
} else if (member !== member) { // NaN
return -1 // Since NaN !== NaN, it will never be found. Fast-path it.
} else // all else
for (; i !== Len; ++i) if (that[i] === member) return i
return -1 // if the value was not found, then return -1
}
})(Object, Math.max, Math.min)
However, if you are more interested in all the little technical bits defined by the ECMA standard, and are less concerned about performance or conciseness, then you may find this more descriptive polyfill to be more useful.
// Production steps of ECMA-262, Edition 5, 15.4.4.14
// Reference: http://es5.github.io/#x15.4.4.14
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function(searchElement, fromIndex) {
"use strict";
var k;
// 1. Let o be the result of calling ToObject passing
// the this value as the argument.
if (this == null) {
throw new TypeError('"this" is null or not defined');
}
var o = Object(this);
// 2. Let lenValue be the result of calling the Get
// internal method of o with the argument "length".
// 3. Let len be ToUint32(lenValue).
var len = o.length >>> 0;
// 4. If len is 0, return -1.
if (len === 0) {
return -1;
}
// 5. If argument fromIndex was passed let n be
// ToInteger(fromIndex); else let n be 0.
var n = fromIndex | 0;
// 6. If n >= len, return -1.
if (n >= len) {
return -1;
}
// 7. If n >= 0, then Let k be n.
// 8. Else, n<0, Let k be len - abs(n).
// If k is less than 0, then let k be 0.
k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);
// 9. Repeat, while k < len
for (; k < len; k++) {
// a. Let Pk be ToString(k).
// This is implicit for LHS operands of the in operator
// b. Let kPresent be the result of calling the
// HasProperty internal method of o with argument Pk.
// This step can be combined with c
// c. If kPresent is true, then
// i. Let elementK be the result of calling the Get
// internal method of o with the argument ToString(k).
// ii. Let same be the result of applying the
// Strict Equality Comparison Algorithm to
// searchElement and elementK.
// iii. If same is true, return k.
if (k in o && o[k] === searchElement)
return k;
}
return -1;
};
}
The lastIndexOf()
method returns the index within the calling String
object of the last occurrence of the specified value, searching backwards from fromIndex
. Returns -1 if the value is not found.
const paragraph = 'The quick brown fox jumps over the lazy dog. If the dog barked, was it really lazy?';
const searchTerm = 'dog';
console.log('The index of the first "' + searchTerm + '" from the end is ' + paragraph.lastIndexOf(searchTerm));
// expected output: "The index of the first "dog" from the end is 52"
str.lastIndexOf(searchValue[, fromIndex])
searchValue
A string representing the value to search for. If searchValue
is an empty string, then fromIndex
is returned.
fromIndex
| Optional
The index of the last character in the string to be considered as the beginning of a match. The default value is +Infinity
. If fromIndex >= str.length
, the whole string is searched. If fromIndex < 0
, the behavior will be the same as if it would be 0
.
The index of the last occurrence of the specified value; -1 if not found.
Characters in a string are indexed from left to right. The index of the first character is 0, and the index of the last character is str.length - 1
.
'canal'.lastIndexOf('a'); // returns 3
'canal'.lastIndexOf('a', 2); // returns 1
'canal'.lastIndexOf('a', 0); // returns -1
'canal'.lastIndexOf('x'); // returns -1
'canal'.lastIndexOf('c', -5); // returns 0
'canal'.lastIndexOf('c', 0); // returns 0
'canal'.lastIndexOf(''); // returns 5
'canal'.lastIndexOf('', 2); // returns 2
Note: 'abab'.lastIndexOf('ab', 2)
will return 2 and not 0, as fromIndex limits only the beginning of the match.
The lastIndexOf()
method is case sensitive. For example, the following expression returns -1:
'Blue Whale, Killer Whale'.lastIndexOf('blue'); // returns -1
indexOf()
and lastIndexOf()
The following example uses indexOf()
and lastIndexOf()
to locate values in the string "Brave new world"
.
var anyString = 'Brave new world';
console.log('The index of the first w from the beginning is ' + anyString.indexOf('w'));
// logs 8
console.log('The index of the first w from the end is ' + anyString.lastIndexOf('w'));
// logs 10
console.log('The index of "new" from the beginning is ' + anyString.indexOf('new'));
// logs 6
console.log('The index of "new" from the end is ' + anyString.lastIndexOf('new'));
// logs 6
#javascript #web-development
1602154740
By the word Array methods, I mean the inbuilt array functions, which might be helpful for us in so many ways. So why not just explore and make use of them, to boost our productivity.
Let’s see them together one by one with some amazing examples.
The
_fill()_
method changes all elements in an array to a static value, from a start index (default_0_
) to an end index (default_array.length_
). It returns the modified array.
In simple words, it’s gonna fill the elements of the array with whatever sets of params, you pass in it. Mostly we pass three params, each param stands with some meaning. The first param value: what value you want to fill, second value: start range of index(inclusive), and third value: end range of index(exclusive). Imagine you are going to apply this method on some date, so that how its gonna look like eg: array.fill(‘Some date’, start date, end date).
NOTE: Start range is inclusive and end range is exclusive.
Let’s understand this in the below example-
//declare array
var testArray = [2,4,6,8,10,12,14];
console.log(testArray.fill("A"));
When you run this code, you gonna see all the elements of testArray
will be replaced by 'A'
like [“A”,"A","A","A","A","A","A"]
.
#javascript-tips #array-methods #javascript-development #javascript #arrays
1624388400
Learn JavaScript Arrays
📺 The video in this post was made by Programming with Mosh
The origin of the article: https://www.youtube.com/watch?v=oigfaZ5ApsM&list=PLTjRvDozrdlxEIuOBZkMAK5uiqp8rHUax&index=4
🔥 If you’re a beginner. I believe the article below will be useful to you ☞ What You Should Know Before Investing in Cryptocurrency - For Beginner
⭐ ⭐ ⭐The project is of interest to the community. Join to Get free ‘GEEK coin’ (GEEKCASH coin)!
☞ **-----CLICK HERE-----**⭐ ⭐ ⭐
Thanks for visiting and watching! Please don’t forget to leave a like, comment and share!
#arrays #javascript #javascript arrays #javascript arrays tutorial
1594911120
In JavaScript, an array is a data structure that contains list of elements which store multiple values in a single variable. The strength of JavaScript arrays lies in the array methods. Array methods are functions built-in to JavaScript that we can apply to our arrays — Each method has a unique function that performs a change or calculation to our array and saves us from writing common functions from scratch.
In this video we are going to learn arrays and array methods like sort(), reverse(), join(), split(), pop(), push(), shift(), unshift(), toString(), delete array, etc…
#javascript #arrays #array methods #programming
1590478483
The easiest approach to use javascript built-in method String.split().
#javascript #javascript string #string to array #morioh #array
1596298980
Arrays are one of the most common things that you’re going to use as a programmer. So, I’m going to explain nine JavaScript array methods that are going to make your life so much easier and more enjoyable.
To get started I just have an array of items, that we’re going to use for all these different array methods. Without wasting much time, let’s dive deep in to the pool of arrays (wink…)
const arrayItems = [
{name: 'cheese cake', price: 25},
{name: 'ham burger', price: 30},
{name: 'cheesy tacos', price: 20},
{name: 'beef burito', price: 18},
{name: 'maxican chille rice', price: 15},
{name: 'hot chocolate', price: 12},
{name: 'apple frudge', price: 28},
{name: 'chicken lassagna', price: 35},
]
So let’s assume that we want to get all the items in this list that are less than or equal to 26 dollars of price. All we need to use is the filter method to filter out everything that’s under 26 dollars. So, let’s just say that, we have a variable which is going to be filteredItems. The filter method just takes a single function which is going to have one parameter.
const filteredItems = arrayItems.filter((item) => {
return item.price <= 26;
})
#web-development #javascript #arrays #array-methods