Removing item from array based on id - javascript

I have two array's. One of id's of elements that I need to show and then another of the elements in a drop down. If the id's match then then show. It sounds simple, but I'm having trouble slicing out the elements that do not need to show.
So it kind of looks like this
var option = //Ton of objects with values that match with the id that look like this, there are about 70 of them. I need to loop through these to get the value of each one. Please see screen shot, I don't know how else to show that they are objects.
var ids = [16, 15, 17, 18, 5];
and then I was trying to loop through each option and see if the value is equal to the Id. For some reason this is removing everything instead of just the once that need to be removed.
for(var i=0 ; i<option.length; i++){
if (option[i].value !== ids) {
option.splice(i);
}
}

Try out the filter function:
var newOptions = options.filter(function(option, index) {
return ids.indexOf(option.value) >= 0;
});
var values = newOptions.map(function(option) {
return option.value;
});

If you want to remove items from the option array:
var option = [
{display:'opt50', value:50 },
{display:'opt16', value:16 },
{display:'opt10', value:10 },
{display:'opt17', value:17 },
{display:'opt43', value:43 },
{display:'opt5', value:5 }
]
var ids = [16, 15, 17, 18, 5];
for(var i = option.length - 1; i > -1; i--) {
if(ids.indexOf(option[i].value) == -1) {
option.splice(i,1);
}
}
// logs [{"display":"opt16","value":16},{"display":"opt17","value":17},{"display":"opt5","value":5}]
console.dir(JSON.stringify(option));
If you want to just find matching items and keep option intact:
// fill in options with some elements
var option = [
{display:'opt50', value:50 },
{display:'opt16', value:16 },
{display:'opt10', value:10 },
{display:'opt17', value:17 },
{display:'opt43', value:43 },
{display:'opt5', value:5 }
]
var ids = [16, 15, 17, 18, 5];
var filteredOption = option.filter(function(o) {
return ids.indexOf(o.value) > -1;
});
// logs [{"display":"opt16","value":16},{"display":"opt17","value":17},{"display":"opt5","value":5}]
console.dir(JSON.stringify(filteredOption));

The !== operator is always going to return true.
12 !== [12,34,45]
true
13 !== [12,34,45]
true
As a result, if (option[i].value !== ids) { will always execute option.splice(i); since the compared values are always different types.
Mozilla's Sameness documentation has a great explanation and useful chart.

var option = [{display: "Member Form",value: 2}, {display: "Member Form",value: 5}];
var ids = [16, 15, 17, 18, 5];
var optionKey = Object.keys(option);
for(var i = optionKey.length - 1; i >= 0 ; i--){
if (ids.indexOf(option[optionKey[i]].value) == -1) {
option.splice(i, 1) //second argument allows splice to only delete one element.
}
}
console.log(option);
document.write(JSON.stringify(option)); //result!

Related

write a function that takes two parameters - an array and a number [duplicate]

Say I've got this
imageList = [100,200,300,400,500];
Which gives me
[0]100 [1]200 etc.
Is there any way in JavaScript to return the index with the value?
I.e. I want the index for 200, I get returned 1.
You can use indexOf:
var imageList = [100,200,300,400,500];
var index = imageList.indexOf(200); // 1
You will get -1 if it cannot find a value in the array.
For objects array use map with indexOf:
var imageList = [
{value: 100},
{value: 200},
{value: 300},
{value: 400},
{value: 500}
];
var index = imageList.map(function (img) { return img.value; }).indexOf(200);
console.log(index);
In modern browsers you can use findIndex:
var imageList = [
{value: 100},
{value: 200},
{value: 300},
{value: 400},
{value: 500}
];
var index = imageList.findIndex(img => img.value === 200);
console.log(index);
Its part of ES6 and supported by Chrome, FF, Safari and Edge
Use jQuery's function
jQuery.inArray
jQuery.inArray( value, array [, fromIndex ] )
(or) $.inArray( value, array [, fromIndex ] )
Here is an another way find value index in complex array in javascript. Hope help somebody indeed.
Let us assume we have a JavaScript array as following,
var studentsArray =
[
{
"rollnumber": 1,
"name": "dj",
"subject": "physics"
},
{
"rollnumber": 2,
"name": "tanmay",
"subject": "biology"
},
{
"rollnumber": 3,
"name": "amit",
"subject": "chemistry"
},
];
Now if we have a requirement to select a particular object in the array. Let us assume that we want to find index of student with name Tanmay.
We can do that by iterating through the array and comparing value at the given key.
function functiontofindIndexByKeyValue(arraytosearch, key, valuetosearch) {
for (var i = 0; i < arraytosearch.length; i++) {
if (arraytosearch[i][key] == valuetosearch) {
return i;
}
}
return null;
}
You can use the function to find index of a particular element as below,
var index = functiontofindIndexByKeyValue(studentsArray, "name", "tanmay");
alert(index);
Use indexOf
imageList.indexOf(200)
how about indexOf ?
alert(imageList.indexOf(200));
Array.indexOf doesnt work in some versions of internet explorer - there are lots of alternative ways of doing it though ... see this question / answer : How do I check if an array includes an object in JavaScript?
When the lists aren't extremely long, this is the best way I know:
function getIndex(val) {
for (var i = 0; i < imageList.length; i++) {
if (imageList[i] === val) {
return i;
}
}
}
var imageList = [100, 200, 300, 400, 500];
var index = getIndex(200);
It is possible to use a ES6 function Array.prototype.findIndex.
MDN says:
The findIndex() method returns the index of the first element in the array that satisfies the provided testing function. Otherwise -1 is returned.
var fooArray = [5, 10, 15, 20, 25];
console.log(fooArray.findIndex(num=> { return num > 5; }));
// expected output: 1
Find an index by object property.
To find an index by object property:
yourArray.findIndex(obj => obj['propertyName'] === yourValue)
For example, there is a such array:
let someArray = [
{ property: 'OutDate' },
{ property: 'BeginDate'},
{ property: 'CarNumber' },
{ property: 'FirstName'}
];
Then, code to find an index of necessary property looks like that:
let carIndex = someArray.findIndex( filterCarObj=>
filterCarObj['property'] === 'CarNumber');
In a multidimensional array.
Reference array:
var array = [
{ ID: '100' },
{ ID: '200' },
{ ID: '300' },
{ ID: '400' },
{ ID: '500' }
];
Using filter and indexOf:
var index = array.indexOf(array.filter(function(item) { return item.ID == '200' })[0]);
Looping through each item in the array using indexOf:
for (var i = 0; i < array.length; i++) {
var item = array[i];
if (item.ID == '200') {
var index = array.indexOf(item);
}
}
Here is my take on it, seems like most peoples solutions don't check if the item exists and it removes random values if it does not exist.
First check if the element exists by looking for it's index.
If it does exist, remove it by its index using the splice method
elementPosition = array.indexOf(value);
if(elementPosition != -1) {
array.splice(elementPosition, 1);
}
// Instead Of
var index = arr.indexOf(200)
// Use
var index = arr.includes(200);
Please Note: Includes function is a simple instance method on the array and helps to easily find if an item is in the array(including NaN unlike indexOf)

Javascript not iterating like expected

Can anyone tell me why my JS is not iterating through the loop and deleting items that are not "10" in the array?
As far as I understand it, it should be checking each item in the array and deleting any that are not 10, then returning the remaining items that are "10".
My current output is: [ <1 empty item>, 10, 50, 10 ]
I've seen some answers that create a separate array and push items that are 10 to it and then return that, but why would my code not work?
function getElementsThatEqual10AtProperty(obj, key) {
if (obj.key.length === 0) {
return [];
} else if (!obj.hasOwnProperty(key)) {
return [];
} else {
for (var i = 0; i < obj.key.length; i++) {
if (obj[key][i] !== 10) {
delete obj[key][i];
}
return obj.key;
}
}
}
var obj = {
key: [1000, 10, 50, 10]
};
var output = getElementsThatEqual10AtProperty(obj, 'key');
console.log(output);
This is a strange design for a method. It mutates and returns a result? Generally, it's better to do one or the other (see CQS).
Also, your original method is overly-coupled to an object structure. It would be better to make it operate on an array only, leaving arbitrary object keys out of it.
Consider the following:
function getElementsThatEqual10(array) {
return array.filter(n => n == 10);
}
var obj = {
key: [1000, 10, 50, 10]
};
var output = getElementsThatEqual10(obj.key);
console.log(output);
The early return breaks out of the loop after it finished deleting the first element only (here simplified to simple array since the object isn't relevant):
let objKey = [1000, 10, 50, 10];
for (var i = 0; i < objKey.length; i++) {
if (objKey[i] !== 10) {
// Here it deletes 1000, the first element
delete objKey[i];
}
// then it returns [undefined, 10, 50, 10]
return objKey;
}
You could move return statement out of the loop to before getElementsThatEqual10AtProperty function ends.
Others have already suggested more elegant ways of doing this.
Well why your code was not working
Your return statement was inside for loop so it will return control as soon as your if condition fails.
You're using delete which will delete the element but the index of other element will still be same as before. so you will get something like [undefined,10,undefined,10].
So here's working mode of you code.
function getElementsThatEqual10AtProperty(obj, key) {
if (obj.key.length === 0) {
return [];
} else if (!obj.hasOwnProperty(key)) {
return [];
} else {
let temp = []
for (var i = 0; i < obj.key.length; i++) {
if (obj[key][i] == 10) {
temp.push(obj[key][i])
}
}
return temp;
}
}
var obj = {
key: [1000, 10, 50, 10]
};
var output = getElementsThatEqual10AtProperty(obj, 'key');
console.log(output);
But i suggest using this one because it's clean and simple
function getElementsThatEqual10(array) {
return array.filter(element => element === 10);
}
var obj = {
key: [1000, 10, 50, 10]
};
var output = getElementsThatEqual10(obj.key);
console.log(output);
What's wrong with your code
The primary issue is that you're doing a return from within the loop, meaning the function will exit completely when it hits that line during your very first iteration.
The second issue is more of a suggestion, but I wouldn't recommend using delete. While the object property is deleted, delete does not update the array's length or or indexes.
var array = [1, 2, 3, 4];
delete array[0];
console.log(array.length);
Hypothetically you could chain a .filter(n=>n) to it and all would be well, but it's still an extra set of unnecessary iterations.
How to resolve it
The easiest way to filter items out of an array is by using the method of that name: Array.filter()
Your updated function could look something like this instead.
function getElementsThatEqual10AtProperty(obj, key) {
if (Array.isArray(obj[key]) //Is it an array?
return obj[key].filter(n => n === 10); //Filter it for 10s
else
return [];
}
var obj = {
key: [1000, 10, 50, 10]
};
var output = getElementsThatEqual10AtProperty(obj, 'key');
console.log(output);
Or, if you prefer brevity:
const get10s = (obj, key) => Array.isArray(obj[key]) ? obj[key].filter(n => n === 10) : [];
var obj = { key: [1000, 10, 50, 10] };
console.log( get10s(obj, 'key') );
Alternative
If you are open to another method, you may try using filter, to parse the values you're after:
const getElementsThatEqual10AtProperty = (obj, key) => obj[key].filter(v => v === 10)
var obj = {
key: [1000, 10, 50, 10]
};
var output = getElementsThatEqual10AtProperty(obj, 'key');
console.log(output);
Your Code
Given your current method there are three issues:
you use obj.key in places that should probably be obj[key] since you are passing key in as an argument
delete obj[key][i] does not behave how you might expect, when operating on an array. As #TinyGiant mentions, "it doesn't reorder the indices to remove the resulting empty slot."
return obj.key should be return obj[key] and it should be moved outside the loop because it is exiting the loop at the end of the first iteration
If you want to keep this method, I would recommend using obj[key].splice(i,1) as opposed to delete, which will alter the array. However, because you are mutating the active array, you will also have to modify the i since the elements have shifted. See below:
function getElementsThatEqual10AtProperty(obj, key) {
if (obj[key].length === 0) {
return [];
} else if (!obj.hasOwnProperty(key)) {
return [];
} else {
for (var i = 0; i < obj.key.length; i++) {
if (obj[key][i] !== 10)
obj[key].splice(i--,1) // remove value then alter i
}
return obj[key] // moved outside of the loop
}
}
var obj = {
key: [1000, 10, 50, 10]
};
var output = getElementsThatEqual10AtProperty(obj, 'key');
console.log(output);
You can write like this to remove the correct items, you were returning inside the for loop so only the first item was being removed.
You can use the splice method instead of delete, because delete only deletes the reference and not the position of the array.
function getElementsThatEqual10AtProperty(obj, key) {
if (obj[key].length === 0) {
return [];
} else if (!obj.hasOwnProperty(key)) {
return [];
} else {
for (var i = 0; i < obj[key].length; i++) {
if (obj[key][i] !== 10) {
obj[key].splice(i, 1);
i--;
}
}
return obj[key];
}
}
var obj = {
key: [1000, 10, 50, 10]
};
var output = getElementsThatEqual10AtProperty(obj, 'key');
console.log(output);

How to get match array index from given ranges array with min max values

How to get matched javascript array index as I expected ?
Range min - First value
Range max - Last value of the given array
var arr = [{
range:[0,20],
title:"First"
data:["a","b"]
},
{
range:[20,40],
title:"Second"
data:["d","f"]
},
{
range:[40,60],
title:"THird"
data:["g","k"]
}];
function getRange( value ){
// retun index of the array
}
getRange( 22 ) -> Expect to get 1 as the array index
getRange( 50 ) -> Expect to get 2 as the array index
Use Array.findIndex
var arr = [{range:[0,20],title:"First",data:["a","b"]},{range:[20,40],title:"Second",data:["d","f"]},{range:[40,60],title:"THird",data:["g","k"]}];
function getRange( value ){
return arr.findIndex(v => value >= v.range[0] && value <= v.range[1]);
}
console.log(getRange(22));
console.log(getRange(50));
Note: As the function counts the range to be inclusive of low and high values, in case of boundary values (20, 40, etc), index of first match will be returned. e.g. in case of 40, index returned will be 1.
1) Note there are a couple of missing commas separating the properties in your data.
2) You need to update your range patterns (0-20, 21-40 etc) to ensure you don't run into problems later.
3) You can use findIndex to return the index of the first object where the value is within the range.
var arr = [{"range":[0,20],"title":"First","data":["a","b"]},{"range":[21,40],"title":"Second","data":["d","f"]},{"range":[41,60],"title":"THird","data":["g","k"]}];
function getRange(arr, value){
// for each object in the array get the range property
return arr.findIndex(({ range }) => {
// and return the first index where the value
// fits within the range
return value >= range[0] && value <= range[1];
});
}
console.log(getRange(arr, 22));
console.log(getRange(arr, 50));
loop over the array and in each range check if the value lies between the values in range.
It may happen that the value is in the range which are in two different index. So it keep an array and push all the index in it
var arr = [{
range: [0, 20],
title: "First",
data: ["a", "b"]
},
{
range: [20, 40],
title: "Second",
data: ["d", "f"]
},
{
range: [40, 60],
title: "THird",
data: ["g", "k"]
}
];
function getRange(value) {
let inxArray = [];
arr.forEach(function(item, index) {
if (value >= item.range[0] && value <= item.range[1]) {
inxArray.push(index)
}
});
return inxArray
}
console.log(getRange(22)[0])
console.log(getRange(50)[0])
You can use Array.findIndex() method:
var arr = [{
range:[0,20],
title:"First",
data:["a","b"]
},
{
range:[20,40],
title:"Second",
data:["d","f"]
},
{
range:[40,60],
title:"THird",
data:["g","k"]
}];
function getRange( value ){
var index = arr.findIndex(obj => obj.range[0] < value && value < obj.range[1]);
return index;
}
console.log(getRange( 22 ));
console.log(getRange( 50 ));
You have to iterate through all array items in order to compare if the value is available within array values range. You can do it through 'for' loop in JS.
Below is the code sample and give a try and play around it:
var arr = [{
range:[0,20],
title:"First"
data:["a","b"]
},
{
range:[20,40],
title:"Second"
data:["d","f"]
},
{
range:[40,60],
title:"THird"
data:["g","k"]
}];
function getRange( value ){
// retun index of the array
for(var i=0; i<arr.length; i++){
if(value > arr[i][0] && value <= arr[i][1]){
return arr[i];
} else{
return null;
}
}
}
Note: Here if the value is "20", then it will return the first array item. Just because we are comparing "<=" in if condition. It doesn't select second array item in your case.
If you are using es6
function getRange( value ){
return arr.findIndex(item=>{
if(value>item.range[0] && value<=item.range[1]){
return true;
}
});
}
If you are not using es6
function getRange( value ){
var flag = -1;
arr.map((item, i)=>{
if(value>item.range[0] && value<=item.range[1]){
flag = i;
}
});
return flag;
}
var arr = [{
range:[0,20],
title:"First",
data:["a","b"]
},
{
range:[20,40],
title:"Second",
data:["d","f"]
},
{
range:[40,60],
title:"THird",
data:["g","k"]
}];
function getRange( value ){
arr.map(a=>
console.log((a.range[0]<=value && a.range[1]>=value)? arr.indexOf(a):'')
);
}
getRange( 22 )// Expect to get 1 as the array index
getRange( 50 ) // Expect to get 2 as the array index
Iterate over the array and check the range in between ranges array then return index.
If I understand correctly, you want getRange(value) to return the item's index where item.range[0] < value && item.range[1] > value.
Because of the way the object is structured, there's nothing in the code to prevent 2 items from having overlapping ranges. In that case, would you want to return the first match, the last match, or some other result? For instance, what would you expect if you called getRange(20) in this example.
Also, your example has some missing commas after the "title" properties.
Ignoring all that, you could use Array.reduce() for a nice terse solution.
function getRange(value) {
return arr.reduce(function(result, item, i) {
if (result === null) {
result = item.range[0] <= value && item.range[1] > value ? i : result;
}
return result;
}, null);
}

javascript associative array access by key value

I have an array like this:
employees = [
{
"id": 1,
"shift_id": 1,
"days": {
"2012-03-01": 1,
"2012-03-02": 1,
"2012-03-03": 1,
"2012-03-04": 0,
"2012-03-05": 0,
"2012-03-06": 0
}},
{
"id": 2,
"shift_id": 1,
"days": {
"2012-03-01": 0,
"2012-03-02": 1,
"2012-03-03": 1,
"2012-03-04": 1,
"2012-03-05": 1,
"2012-03-06": 0
}},
{
"id": 3,
"shift_id": 2,
"days": {
"2012-03-01": 0,
"2012-03-02": 0,
"2012-03-03": 1,
"2012-03-04": 1,
"2012-03-05": 1,
"2012-03-06": 1
}}
];
is there a way to access an element in this array using the id value?
maybe something in jquery?
like $(employees('id = 1');
Just loop through your array and check for the id:
var yourId = 1;
for (var i = 0, len = employees.length; i < len; i++) {
if (employees[i].id == yourId) {
// ...
}
}
You can use a function like this, which filters the array appropriately:
var getEmployee = function (id) {
return employees.filter(function(i) { return i.id == id; });
};
You can use .grep() method documented here:
var employee = $.grep(employees, function(e) { return e.id == 1 })[0];
Well, there's a jQuery way of doing it:
var findElementById = function(elements, id) {
return $.grep(elements, function(e) { return e.id === id; })[0];
}
Still I wonder why don't you just index the source array by id instead.
Maybe you are looking for something like the below:
$.grep(employees, function(n){return n.id==1});
Or this:
$.each(employee, function(){
if(this["id"] == 2){
console.log(this);
}
});
As far as I am aware, in order to achieve that you would have to loop through them
Array.prototype.getObjectById = function(x){
var catcher = false, i = 0;
while(!catcher){
catcher = this[i].id == x ? this[i] : false;
i++;
}
return catcher;
}
This function should help. It will extend the array object so you can use it as myArray.getObjectbyId(id);
By design, this will return the first object that meets the criteria. You could extend it like so:
Array.prototype.getObjectsById = function(x){
var catcher = [], i = 0;
for(var i = 0; i < this.length; i++){
if(this[i].id == value){
catcher.push(this[i]);
}
i++;
}
return catcher.length == 1 ? catcher[0] : catcher;
}
This will return an array of objects if more than one object matches the criteria.
Array.prototype.getObjectsByAttribute = function(x, criteria){
if(!criteria){criteria = 'id';}
var catcher = [], i = 0;
for(var i = 0; i < this.length; i++){
if(this[i].criteria == value){
catcher.push(this[i]);
}
i++;
}
return catcher.length == 1 ? catcher[0] : catcher;
}
This extends it further to look for any criteria.
I know this question is old, but for future reference if anyone else stumbles upon this question ...
Instead of trying to over-engineer a function to parse/examine your JSON, consider changing the structure of your data to suit its purpose.
Consider the example in the question:
data = [ {
"id": 1,
"shift_id": 1,
"days": {
"2012-03-01": 1,
"2012-03-02": 1,
"2012-03-03": 1,
"2012-03-04": 0,
"2012-03-05": 0,
"2012-03-06": 0
}}, { .. }, {...} ]
Structuring the data in this way only gives you sequential access to the objects with no way to lookup an object by a particular index. Array indices are generally meaningless in this context.
data[0] => { id : 1, .. }
data[1] => { id : 2, .. }
What happens if the id is non-sequential or alphanumeric?
Using an array wont help you search any faster, you'll still have to loop...
Instead consider using a hash table/object:
{
'id1' => { id : 1 , data : { ... } },
'id99' => { id : 99, data : { ... } },
'id2' => { id : 2 , data : { ... } },
}
You can use a string value for the key and get direct access to the data by doing something like:
data['id2'] => { id : 2, ... }
Which will give you direct access to the data you want to find (by id). By simply re-organizing the structure of the data we were able to go from a O(n) search to an O(1) search.
Keep in mind that this method may work better for some solutions than others, and there are a number of other considerations to make.
This is just one approach to how you might solve a problem when you want to lookup data by a unique property.
The accepted answer is great - modified a bit for an AngularJS app:
$rootScope.getObjectsByAttribute = function(inarry,infldnm,infldval){
// This will iterate through a fetchAll sql result set and return rows where fldnm==fldval
// If it finds 1 row it returns a single object, if more than that it returns an array of objects
// Usage: result = $rootScope.getObjectsByAttribute(myarray,'myfldnm',myfldval);
if(!infldnm){infldnm = 'id';}
var catcher = [], i = 0;
for(i = 0; i < inarry.length; i++){
if(inarry[i][infldnm] == infldval){
catcher.push(inarry[i]);
}
}
return catcher.length == 1 ? catcher[0] : catcher;
}

How to find the array index with a value?

Say I've got this
imageList = [100,200,300,400,500];
Which gives me
[0]100 [1]200 etc.
Is there any way in JavaScript to return the index with the value?
I.e. I want the index for 200, I get returned 1.
You can use indexOf:
var imageList = [100,200,300,400,500];
var index = imageList.indexOf(200); // 1
You will get -1 if it cannot find a value in the array.
For objects array use map with indexOf:
var imageList = [
{value: 100},
{value: 200},
{value: 300},
{value: 400},
{value: 500}
];
var index = imageList.map(function (img) { return img.value; }).indexOf(200);
console.log(index);
In modern browsers you can use findIndex:
var imageList = [
{value: 100},
{value: 200},
{value: 300},
{value: 400},
{value: 500}
];
var index = imageList.findIndex(img => img.value === 200);
console.log(index);
Its part of ES6 and supported by Chrome, FF, Safari and Edge
Use jQuery's function
jQuery.inArray
jQuery.inArray( value, array [, fromIndex ] )
(or) $.inArray( value, array [, fromIndex ] )
Here is an another way find value index in complex array in javascript. Hope help somebody indeed.
Let us assume we have a JavaScript array as following,
var studentsArray =
[
{
"rollnumber": 1,
"name": "dj",
"subject": "physics"
},
{
"rollnumber": 2,
"name": "tanmay",
"subject": "biology"
},
{
"rollnumber": 3,
"name": "amit",
"subject": "chemistry"
},
];
Now if we have a requirement to select a particular object in the array. Let us assume that we want to find index of student with name Tanmay.
We can do that by iterating through the array and comparing value at the given key.
function functiontofindIndexByKeyValue(arraytosearch, key, valuetosearch) {
for (var i = 0; i < arraytosearch.length; i++) {
if (arraytosearch[i][key] == valuetosearch) {
return i;
}
}
return null;
}
You can use the function to find index of a particular element as below,
var index = functiontofindIndexByKeyValue(studentsArray, "name", "tanmay");
alert(index);
Use indexOf
imageList.indexOf(200)
how about indexOf ?
alert(imageList.indexOf(200));
Array.indexOf doesnt work in some versions of internet explorer - there are lots of alternative ways of doing it though ... see this question / answer : How do I check if an array includes an object in JavaScript?
When the lists aren't extremely long, this is the best way I know:
function getIndex(val) {
for (var i = 0; i < imageList.length; i++) {
if (imageList[i] === val) {
return i;
}
}
}
var imageList = [100, 200, 300, 400, 500];
var index = getIndex(200);
It is possible to use a ES6 function Array.prototype.findIndex.
MDN says:
The findIndex() method returns the index of the first element in the array that satisfies the provided testing function. Otherwise -1 is returned.
var fooArray = [5, 10, 15, 20, 25];
console.log(fooArray.findIndex(num=> { return num > 5; }));
// expected output: 1
Find an index by object property.
To find an index by object property:
yourArray.findIndex(obj => obj['propertyName'] === yourValue)
For example, there is a such array:
let someArray = [
{ property: 'OutDate' },
{ property: 'BeginDate'},
{ property: 'CarNumber' },
{ property: 'FirstName'}
];
Then, code to find an index of necessary property looks like that:
let carIndex = someArray.findIndex( filterCarObj=>
filterCarObj['property'] === 'CarNumber');
In a multidimensional array.
Reference array:
var array = [
{ ID: '100' },
{ ID: '200' },
{ ID: '300' },
{ ID: '400' },
{ ID: '500' }
];
Using filter and indexOf:
var index = array.indexOf(array.filter(function(item) { return item.ID == '200' })[0]);
Looping through each item in the array using indexOf:
for (var i = 0; i < array.length; i++) {
var item = array[i];
if (item.ID == '200') {
var index = array.indexOf(item);
}
}
Here is my take on it, seems like most peoples solutions don't check if the item exists and it removes random values if it does not exist.
First check if the element exists by looking for it's index.
If it does exist, remove it by its index using the splice method
elementPosition = array.indexOf(value);
if(elementPosition != -1) {
array.splice(elementPosition, 1);
}
// Instead Of
var index = arr.indexOf(200)
// Use
var index = arr.includes(200);
Please Note: Includes function is a simple instance method on the array and helps to easily find if an item is in the array(including NaN unlike indexOf)

Categories