I have an array like
vendors = [{
Name: 'Magenic',
ID: 'ABC'
},
{
Name: 'Microsoft',
ID: 'DEF'
} // and so on...
];
How do I check this array to see if "Magenic" exists? I don't want to loop, unless I have to. I'm working with potentially a couple thousand records.
No need to reinvent the wheel loop, at least not explicitly (using arrow functions, modern browsers only):
if (vendors.filter(e => e.Name === 'Magenic').length > 0) {
/* vendors contains the element we're looking for */
}
or, better yet, use some as it allows the browser to stop as soon as one element is found that matches, so it's going to be faster:
if (vendors.some(e => e.Name === 'Magenic')) {
/* vendors contains the element we're looking for */
}
or the equivalent (in this case) find:
if (vendors.find(e => e.Name === 'Magenic')) {
/* same result as above, but a different function return type */
}
And you can even get the position of that element by using findIndex:
const i = vendors.findIndex(e => e.Name === 'Magenic');
if (i > -1) {
/* vendors contains the element we're looking for, at index "i" */
}
And if you need compatibility with lousy browsers then your best bet is:
if (vendors.filter(function(e) { return e.Name === 'Magenic'; }).length > 0) {
/* vendors contains the element we're looking for */
}
2018 edit: This answer is from 2011, before browsers had widely supported array filtering methods and arrow functions. Have a look at CAFxX's answer.
There is no "magic" way to check for something in an array without a loop. Even if you use some function, the function itself will use a loop. What you can do is break out of the loop as soon as you find what you're looking for to minimize computational time.
var found = false;
for(var i = 0; i < vendors.length; i++) {
if (vendors[i].Name == 'Magenic') {
found = true;
break;
}
}
No loop necessary. Three methods that come to mind:
Array.prototype.some()
This is the most exact answer for your question, i.e. "check if something exists", implying a bool result. This will be true if there are any 'Magenic' objects, false otherwise:
let hasMagenicVendor = vendors.some( vendor => vendor['Name'] === 'Magenic' )
Array.prototype.filter()
This will return an array of all 'Magenic' objects, even if there is only one (will return a one-element array):
let magenicVendors = vendors.filter( vendor => vendor['Name'] === 'Magenic' )
If you try to coerce this to a boolean, it will not work, as an empty array (no 'Magenic' objects) is still truthy. So just use magenicVendors.length in your conditional.
Array.prototype.find()
This will return the first 'Magenic' object (or undefined if there aren't any):
let magenicVendor = vendors.find( vendor => vendor['Name'] === 'Magenic' );
This coerces to a boolean okay (any object is truthy, undefined is falsy).
Note: I'm using vendor["Name"] instead of vendor.Name because of the weird casing of the property names.
Note 2: No reason to use loose equality (==) instead of strict equality (===) when checking the name.
The accepted answer still works but now we have an ECMAScript 6 native methods [Array.find][1] and [Array.some][2] to achieve the same effect.
Array.some
Use some If you only want to determine if an element exists i.e. you need a true/false determination.
Quoting MDN:
The some() method tests whether at least one element in the array passes the test implemented by the provided function. It returns true if, in the array, it finds an element for which the provided function returns true; otherwise it returns false. It doesn't modify the array.
Array.find
Use find if you want to get the matched object from array else returns undefined.
Quoting MDN:
The find() method returns the value of the first element in the provided array that satisfies the provided testing function. If no values satisfy the testing function, undefined is returned.
var arr = [
{
id: 21,
label: 'Banana',
},
{
id: 22,
label: 'Apple',
}
]
/* note : data is the actual object that matched search criteria
or undefined if nothing matched */
var data = arr.find(function(ele) {
return ele.id === 21;
});
if (data) {
console.log('found');
console.log(data); // This is entire object i.e. `item` not boolean
}
/* note : doesExist is a boolean thats true or false depending on of whether the data was found or not */
var doesExist = arr.some(function(ele) {
return ele.id === 21;
});
See my jsfiddle link There is a polyfill for IE provided by mozilla
Here's the way I'd do it
const found = vendors.some(item => item.Name === 'Magenic');
array.some() method checks if there is at least one value in an array that matches criteria and returns a boolean.
From here on you can go with:
if (found) {
// do something
} else {
// do something else
}
Unless you want to restructure it like this:
vendors = {
Magenic: {
Name: 'Magenic',
ID: 'ABC'
},
Microsoft: {
Name: 'Microsoft',
ID: 'DEF'
} and so on...
};
to which you can do if(vendors.Magnetic)
You will have to loop
May be too late, but javascript array has two methods some and every method that returns a boolean and can help you achieve this.
I think some would be most appropriate for what you intend to achieve.
vendors.some( vendor => vendor['Name'] !== 'Magenic' )
Some validates that any of the objects in the array satisfies the given condition.
vendors.every( vendor => vendor['Name'] !== 'Magenic' )
Every validates that all the objects in the array satisfies the given condition.
As per ECMAScript 6 specification, you can use findIndex.
const magenicIndex = vendors.findIndex(vendor => vendor.Name === 'Magenic');
magenicIndex will hold either 0 (which is the index in the array) or -1 if it wasn't found.
As the OP has asked the question if the key exists or not.
A more elegant solution that will return boolean using ES6 reduce function can be
const magenicVendorExists = vendors.reduce((accumulator, vendor) => (accumulator||vendor.Name === "Magenic"), false);
Note: The initial parameter of reduce is a false and if the array has the key it will return true.
Hope it helps for better and cleaner code implementation
You cannot without looking into the object really.
You probably should change your structure a little, like
vendors = {
Magenic: 'ABC',
Microsoft: 'DEF'
};
Then you can just use it like a lookup-hash.
vendors['Microsoft']; // 'DEF'
vendors['Apple']; // undefined
const check = vendors.find((item)=>item.Name==='Magenic')
console.log(check)
Try this code.
If the item or element is present then the output will show you that element. If it is not present then the output will be 'undefined'.
Testing for array elements:
JS Offers array functions which allow you to achieve this relatively easily. They are the following:
Array.prototype.filter: Takes a callback function which is a test, the array is then iterated over with is callback and filtered according to this callback. A new filtered array is returned.
Array.prototype.some: Takes a callback function which is a test, the array is then iterated over with is callback and if any element passes the test, the boolean true is returned. Otherwise false is returned
The specifics are best explained via an example:
Example:
vendors = [
{
Name: 'Magenic',
ID: 'ABC'
},
{
Name: 'Microsoft',
ID: 'DEF'
} //and so on goes array...
];
// filter returns a new array, we instantly check if the length
// is longer than zero of this newly created array
if (vendors.filter(company => company.Name === 'Magenic').length ) {
console.log('I contain Magenic');
}
// some would be a better option then filter since it directly returns a boolean
if (vendors.some(company => company.Name === 'Magenic')) {
console.log('I also contain Magenic');
}
Browser support:
These 2 function are ES6 function, not all browsers might support them. To overcome this you can use a polyfill. Here is the polyfill for Array.prototype.some (from MDN):
if (!Array.prototype.some) {
Array.prototype.some = function(fun, thisArg) {
'use strict';
if (this == null) {
throw new TypeError('Array.prototype.some called on null or undefined');
}
if (typeof fun !== 'function') {
throw new TypeError();
}
var t = Object(this);
var len = t.length >>> 0;
for (var i = 0; i < len; i++) {
if (i in t && fun.call(thisArg, t[i], i, t)) {
return true;
}
}
return false;
};
}
Simplest method so far:
if (vendors.findIndex(item => item.Name == "Magenic") == -1) {
//not found item
} else {
//found item
}
My approach to solving this problem is to use ES6 and creating a function that does the check for us. The benefit of this function is that it can be reusable through out your project to check any array of objects given the key and the value to check.
ENOUGH TALK, LET'S SEE THE CODE
Array
const ceos = [
{
name: "Jeff Bezos",
company: "Amazon"
},
{
name: "Mark Zuckerberg",
company: "Facebook"
},
{
name: "Tim Cook",
company: "Apple"
}
];
Function
const arrayIncludesInObj = (arr, key, valueToCheck) => {
return arr.some(value => value[key] === valueToCheck);
}
Call/Usage
const found = arrayIncludesInObj(ceos, "name", "Tim Cook"); // true
const found = arrayIncludesInObj(ceos, "name", "Tim Bezos"); // false
2021 Solution*
Lodash .some (docs) is a clean solution, if you use the _matchesProperty (docs) shorthand:
_.some(VENDORS, ['Name', 'Magenic'])
Explanation
This will iterate through the VENDORS Array looking for an element Object with the Name key having a value of the String 'Magenic'. Once it finds this element, it returns true and stops iterating. If it doesn't find the element after looking through the entire Array, it returns false.
Code snippet
const VENDORS = [{ Name: 'Magenic', ID: 'ABC' }, { Name: 'Microsoft', ID: 'DEF' }];
console.log(_.some(VENDORS, ['Name', 'Magenic'])); // true
<script src="https://cdn.jsdelivr.net/npm/lodash#4.17.20/lodash.min.js"></script>
* Note that this uses the popular lodash library to achieve the simplest/shortest possible solution. I'm offering this as an alternative to the existing vanilla JS solutions, for those who are interested.
You have to loop, there is no way around it.
function seekVendor(vendors, name) {
for (var i=0, l=vendors.length; i<l; i++) {
if (typeof vendors[i] == "object" && vendors[i].Name === name) {
return vendors[i];
}
}
}
Of course you could use a library like linq.js to make this more pleasing:
Enumerable.From(vendors).Where("$.Name == 'Magenic'").First();
(see jsFiddle for a demo)
I doubt that linq.js will be faster than a straight-forward loop, but it certainly is more flexible when things get a little more complicated.
Correct me if i'm wrong..
i could have used forEach method like this,
var found=false;
vendors.forEach(function(item){
if(item.name === "name"){
found=true;
}
});
Nowadays i'm used to it ,because of it simplicity and self explanatory word.
Thank you.
Functions map, filter, find, and similar are slower than the simple loop.
For me they also less readable than the simple loop and harder to debug. Using them looks like a kind of irrational ritual.
Better have something like this:
arrayHelper = {
arrayContainsObject: function (array, object, key){
for (let i = 0; i < array.length; i++){
if (object[key] === array[i][key]){
return true;
}
}
return false;
}
};
And use it like this with given OP example:
vendors = [{
Name: 'Magenic',
ID: 'ABC'
},
{
Name: 'Microsoft',
ID: 'DEF'
}
];
let abcObject = {ID: 'ABC', Name: 'Magenic'};
let isContainObject = arrayHelper.arrayContainsObject(vendors, abcObject, 'ID');
if you're using jquery you can take advantage of grep to create array with all matching objects:
var results = $.grep(vendors, function (e) {
return e.Name == "Magenic";
});
and then use the results array:
for (var i=0, l=results.length; i<l; i++) {
console.log(results[i].ID);
}
You can use lodash. If lodash library is too heavy for your application consider chunking out unnecessary function not used.
let newArray = filter(_this.props.ArrayOne, function(item) {
return find(_this.props.ArrayTwo, {"speciesId": item.speciesId});
});
This is just one way to do this. Another one can be:
var newArray= [];
_.filter(ArrayOne, function(item) {
return AllSpecies.forEach(function(cItem){
if (cItem.speciesId == item.speciesId){
newArray.push(item);
}
})
});
console.log(arr);
The above example can also be rewritten without using any libraries like:
var newArray= [];
ArrayOne.filter(function(item) {
return ArrayTwo.forEach(function(cItem){
if (cItem.speciesId == item.speciesId){
newArray.push(item);
}
})
});
console.log(arr);
Hope my answer helps.
Many answers here are good and pretty easy. But if your array of object is having a fixed set of value then you can use below trick:
Map all the name in a object.
vendors = [
{
Name: 'Magenic',
ID: 'ABC'
},
{
Name: 'Microsoft',
ID: 'DEF'
}
];
var dirtyObj = {}
for(var count=0;count<vendors.length;count++){
dirtyObj[vendors[count].Name] = true //or assign which gives you true.
}
Now this dirtyObj you can use again and again without any loop.
if(dirtyObj[vendor.Name]){
console.log("Hey! I am available.");
}
To compare one object to another, I combine a for in loop (used to loop through objects) and some().
You do not have to worry about an array going out of bounds etc, so that saves some code. Documentation on .some can be found here
var productList = [{id: 'text3'}, {id: 'text2'}, {id: 'text4', product: 'Shampoo'}]; // Example of selected products
var theDatabaseList = [{id: 'text1'}, {id: 'text2'},{id: 'text3'},{id:'text4', product: 'shampoo'}];
var objectsFound = [];
for(let objectNumber in productList){
var currentId = productList[objectNumber].id;
if (theDatabaseList.some(obj => obj.id === currentId)) {
// Do what you need to do with the matching value here
objectsFound.push(currentId);
}
}
console.log(objectsFound);
An alternative way I compare one object to another is to use a nested for loop with Object.keys().length to get the amount of objects in the array. Code below:
var productList = [{id: 'text3'}, {id: 'text2'}, {id: 'text4', product: 'Shampoo'}]; // Example of selected products
var theDatabaseList = [{id: 'text1'}, {id: 'text2'},{id: 'text3'},{id:'text4', product: 'shampoo'}];
var objectsFound = [];
for(var i = 0; i < Object.keys(productList).length; i++){
for(var j = 0; j < Object.keys(theDatabaseList).length; j++){
if(productList[i].id === theDatabaseList[j].id){
objectsFound.push(productList[i].id);
}
}
}
console.log(objectsFound);
To answer your exact question, if are just searching for a value in an object, you can use a single for in loop.
var vendors = [
{
Name: 'Magenic',
ID: 'ABC'
},
{
Name: 'Microsoft',
ID: 'DEF'
}
];
for(var ojectNumbers in vendors){
if(vendors[ojectNumbers].Name === 'Magenic'){
console.log('object contains Magenic');
}
}
Alternatively you can do:
const find = (key, needle) => return !!~vendors.findIndex(v => (v[key] === needle));
var without2 = (arr, args) => arr.filter(v => v.id !== args.id);
Example:
without2([{id:1},{id:1},{id:2}],{id:2})
Result:
without2([{id:1},{id:1},{id:2}],{id:2})
You can try this its work for me.
const _ = require('lodash');
var arr = [
{
name: 'Jack',
id: 1
},
{
name: 'Gabriel',
id: 2
},
{
name: 'John',
id: 3
}
]
function findValue(arr,value) {
return _.filter(arr, function (object) {
return object['name'].toLowerCase().indexOf(value.toLowerCase()) >= 0;
});
}
console.log(findValue(arr,'jack'))
//[ { name: 'Jack', id: 1 } ]
const a = [{one:2},{two:2},{two:4}]
const b = a.filter(val => "two" in val).length;
if (b) {
...
}
I would rather go with regex.
If your code is as follows,
vendors = [
{
Name: 'Magenic',
ID: 'ABC'
},
{
Name: 'Microsoft',
ID: 'DEF'
}
];
I would recommend
/"Name":"Magenic"/.test(JSON.stringify(vendors))
Related
I have an array like
vendors = [{
Name: 'Magenic',
ID: 'ABC'
},
{
Name: 'Microsoft',
ID: 'DEF'
} // and so on...
];
How do I check this array to see if "Magenic" exists? I don't want to loop, unless I have to. I'm working with potentially a couple thousand records.
No need to reinvent the wheel loop, at least not explicitly (using arrow functions, modern browsers only):
if (vendors.filter(e => e.Name === 'Magenic').length > 0) {
/* vendors contains the element we're looking for */
}
or, better yet, use some as it allows the browser to stop as soon as one element is found that matches, so it's going to be faster:
if (vendors.some(e => e.Name === 'Magenic')) {
/* vendors contains the element we're looking for */
}
or the equivalent (in this case) find:
if (vendors.find(e => e.Name === 'Magenic')) {
/* same result as above, but a different function return type */
}
And you can even get the position of that element by using findIndex:
const i = vendors.findIndex(e => e.Name === 'Magenic');
if (i > -1) {
/* vendors contains the element we're looking for, at index "i" */
}
And if you need compatibility with lousy browsers then your best bet is:
if (vendors.filter(function(e) { return e.Name === 'Magenic'; }).length > 0) {
/* vendors contains the element we're looking for */
}
2018 edit: This answer is from 2011, before browsers had widely supported array filtering methods and arrow functions. Have a look at CAFxX's answer.
There is no "magic" way to check for something in an array without a loop. Even if you use some function, the function itself will use a loop. What you can do is break out of the loop as soon as you find what you're looking for to minimize computational time.
var found = false;
for(var i = 0; i < vendors.length; i++) {
if (vendors[i].Name == 'Magenic') {
found = true;
break;
}
}
No loop necessary. Three methods that come to mind:
Array.prototype.some()
This is the most exact answer for your question, i.e. "check if something exists", implying a bool result. This will be true if there are any 'Magenic' objects, false otherwise:
let hasMagenicVendor = vendors.some( vendor => vendor['Name'] === 'Magenic' )
Array.prototype.filter()
This will return an array of all 'Magenic' objects, even if there is only one (will return a one-element array):
let magenicVendors = vendors.filter( vendor => vendor['Name'] === 'Magenic' )
If you try to coerce this to a boolean, it will not work, as an empty array (no 'Magenic' objects) is still truthy. So just use magenicVendors.length in your conditional.
Array.prototype.find()
This will return the first 'Magenic' object (or undefined if there aren't any):
let magenicVendor = vendors.find( vendor => vendor['Name'] === 'Magenic' );
This coerces to a boolean okay (any object is truthy, undefined is falsy).
Note: I'm using vendor["Name"] instead of vendor.Name because of the weird casing of the property names.
Note 2: No reason to use loose equality (==) instead of strict equality (===) when checking the name.
The accepted answer still works but now we have an ECMAScript 6 native methods [Array.find][1] and [Array.some][2] to achieve the same effect.
Array.some
Use some If you only want to determine if an element exists i.e. you need a true/false determination.
Quoting MDN:
The some() method tests whether at least one element in the array passes the test implemented by the provided function. It returns true if, in the array, it finds an element for which the provided function returns true; otherwise it returns false. It doesn't modify the array.
Array.find
Use find if you want to get the matched object from array else returns undefined.
Quoting MDN:
The find() method returns the value of the first element in the provided array that satisfies the provided testing function. If no values satisfy the testing function, undefined is returned.
var arr = [
{
id: 21,
label: 'Banana',
},
{
id: 22,
label: 'Apple',
}
]
/* note : data is the actual object that matched search criteria
or undefined if nothing matched */
var data = arr.find(function(ele) {
return ele.id === 21;
});
if (data) {
console.log('found');
console.log(data); // This is entire object i.e. `item` not boolean
}
/* note : doesExist is a boolean thats true or false depending on of whether the data was found or not */
var doesExist = arr.some(function(ele) {
return ele.id === 21;
});
See my jsfiddle link There is a polyfill for IE provided by mozilla
Here's the way I'd do it
const found = vendors.some(item => item.Name === 'Magenic');
array.some() method checks if there is at least one value in an array that matches criteria and returns a boolean.
From here on you can go with:
if (found) {
// do something
} else {
// do something else
}
Unless you want to restructure it like this:
vendors = {
Magenic: {
Name: 'Magenic',
ID: 'ABC'
},
Microsoft: {
Name: 'Microsoft',
ID: 'DEF'
} and so on...
};
to which you can do if(vendors.Magnetic)
You will have to loop
May be too late, but javascript array has two methods some and every method that returns a boolean and can help you achieve this.
I think some would be most appropriate for what you intend to achieve.
vendors.some( vendor => vendor['Name'] !== 'Magenic' )
Some validates that any of the objects in the array satisfies the given condition.
vendors.every( vendor => vendor['Name'] !== 'Magenic' )
Every validates that all the objects in the array satisfies the given condition.
As per ECMAScript 6 specification, you can use findIndex.
const magenicIndex = vendors.findIndex(vendor => vendor.Name === 'Magenic');
magenicIndex will hold either 0 (which is the index in the array) or -1 if it wasn't found.
As the OP has asked the question if the key exists or not.
A more elegant solution that will return boolean using ES6 reduce function can be
const magenicVendorExists = vendors.reduce((accumulator, vendor) => (accumulator||vendor.Name === "Magenic"), false);
Note: The initial parameter of reduce is a false and if the array has the key it will return true.
Hope it helps for better and cleaner code implementation
You cannot without looking into the object really.
You probably should change your structure a little, like
vendors = {
Magenic: 'ABC',
Microsoft: 'DEF'
};
Then you can just use it like a lookup-hash.
vendors['Microsoft']; // 'DEF'
vendors['Apple']; // undefined
const check = vendors.find((item)=>item.Name==='Magenic')
console.log(check)
Try this code.
If the item or element is present then the output will show you that element. If it is not present then the output will be 'undefined'.
Testing for array elements:
JS Offers array functions which allow you to achieve this relatively easily. They are the following:
Array.prototype.filter: Takes a callback function which is a test, the array is then iterated over with is callback and filtered according to this callback. A new filtered array is returned.
Array.prototype.some: Takes a callback function which is a test, the array is then iterated over with is callback and if any element passes the test, the boolean true is returned. Otherwise false is returned
The specifics are best explained via an example:
Example:
vendors = [
{
Name: 'Magenic',
ID: 'ABC'
},
{
Name: 'Microsoft',
ID: 'DEF'
} //and so on goes array...
];
// filter returns a new array, we instantly check if the length
// is longer than zero of this newly created array
if (vendors.filter(company => company.Name === 'Magenic').length ) {
console.log('I contain Magenic');
}
// some would be a better option then filter since it directly returns a boolean
if (vendors.some(company => company.Name === 'Magenic')) {
console.log('I also contain Magenic');
}
Browser support:
These 2 function are ES6 function, not all browsers might support them. To overcome this you can use a polyfill. Here is the polyfill for Array.prototype.some (from MDN):
if (!Array.prototype.some) {
Array.prototype.some = function(fun, thisArg) {
'use strict';
if (this == null) {
throw new TypeError('Array.prototype.some called on null or undefined');
}
if (typeof fun !== 'function') {
throw new TypeError();
}
var t = Object(this);
var len = t.length >>> 0;
for (var i = 0; i < len; i++) {
if (i in t && fun.call(thisArg, t[i], i, t)) {
return true;
}
}
return false;
};
}
Simplest method so far:
if (vendors.findIndex(item => item.Name == "Magenic") == -1) {
//not found item
} else {
//found item
}
My approach to solving this problem is to use ES6 and creating a function that does the check for us. The benefit of this function is that it can be reusable through out your project to check any array of objects given the key and the value to check.
ENOUGH TALK, LET'S SEE THE CODE
Array
const ceos = [
{
name: "Jeff Bezos",
company: "Amazon"
},
{
name: "Mark Zuckerberg",
company: "Facebook"
},
{
name: "Tim Cook",
company: "Apple"
}
];
Function
const arrayIncludesInObj = (arr, key, valueToCheck) => {
return arr.some(value => value[key] === valueToCheck);
}
Call/Usage
const found = arrayIncludesInObj(ceos, "name", "Tim Cook"); // true
const found = arrayIncludesInObj(ceos, "name", "Tim Bezos"); // false
2021 Solution*
Lodash .some (docs) is a clean solution, if you use the _matchesProperty (docs) shorthand:
_.some(VENDORS, ['Name', 'Magenic'])
Explanation
This will iterate through the VENDORS Array looking for an element Object with the Name key having a value of the String 'Magenic'. Once it finds this element, it returns true and stops iterating. If it doesn't find the element after looking through the entire Array, it returns false.
Code snippet
const VENDORS = [{ Name: 'Magenic', ID: 'ABC' }, { Name: 'Microsoft', ID: 'DEF' }];
console.log(_.some(VENDORS, ['Name', 'Magenic'])); // true
<script src="https://cdn.jsdelivr.net/npm/lodash#4.17.20/lodash.min.js"></script>
* Note that this uses the popular lodash library to achieve the simplest/shortest possible solution. I'm offering this as an alternative to the existing vanilla JS solutions, for those who are interested.
You have to loop, there is no way around it.
function seekVendor(vendors, name) {
for (var i=0, l=vendors.length; i<l; i++) {
if (typeof vendors[i] == "object" && vendors[i].Name === name) {
return vendors[i];
}
}
}
Of course you could use a library like linq.js to make this more pleasing:
Enumerable.From(vendors).Where("$.Name == 'Magenic'").First();
(see jsFiddle for a demo)
I doubt that linq.js will be faster than a straight-forward loop, but it certainly is more flexible when things get a little more complicated.
Correct me if i'm wrong..
i could have used forEach method like this,
var found=false;
vendors.forEach(function(item){
if(item.name === "name"){
found=true;
}
});
Nowadays i'm used to it ,because of it simplicity and self explanatory word.
Thank you.
Functions map, filter, find, and similar are slower than the simple loop.
For me they also less readable than the simple loop and harder to debug. Using them looks like a kind of irrational ritual.
Better have something like this:
arrayHelper = {
arrayContainsObject: function (array, object, key){
for (let i = 0; i < array.length; i++){
if (object[key] === array[i][key]){
return true;
}
}
return false;
}
};
And use it like this with given OP example:
vendors = [{
Name: 'Magenic',
ID: 'ABC'
},
{
Name: 'Microsoft',
ID: 'DEF'
}
];
let abcObject = {ID: 'ABC', Name: 'Magenic'};
let isContainObject = arrayHelper.arrayContainsObject(vendors, abcObject, 'ID');
if you're using jquery you can take advantage of grep to create array with all matching objects:
var results = $.grep(vendors, function (e) {
return e.Name == "Magenic";
});
and then use the results array:
for (var i=0, l=results.length; i<l; i++) {
console.log(results[i].ID);
}
You can use lodash. If lodash library is too heavy for your application consider chunking out unnecessary function not used.
let newArray = filter(_this.props.ArrayOne, function(item) {
return find(_this.props.ArrayTwo, {"speciesId": item.speciesId});
});
This is just one way to do this. Another one can be:
var newArray= [];
_.filter(ArrayOne, function(item) {
return AllSpecies.forEach(function(cItem){
if (cItem.speciesId == item.speciesId){
newArray.push(item);
}
})
});
console.log(arr);
The above example can also be rewritten without using any libraries like:
var newArray= [];
ArrayOne.filter(function(item) {
return ArrayTwo.forEach(function(cItem){
if (cItem.speciesId == item.speciesId){
newArray.push(item);
}
})
});
console.log(arr);
Hope my answer helps.
Many answers here are good and pretty easy. But if your array of object is having a fixed set of value then you can use below trick:
Map all the name in a object.
vendors = [
{
Name: 'Magenic',
ID: 'ABC'
},
{
Name: 'Microsoft',
ID: 'DEF'
}
];
var dirtyObj = {}
for(var count=0;count<vendors.length;count++){
dirtyObj[vendors[count].Name] = true //or assign which gives you true.
}
Now this dirtyObj you can use again and again without any loop.
if(dirtyObj[vendor.Name]){
console.log("Hey! I am available.");
}
To compare one object to another, I combine a for in loop (used to loop through objects) and some().
You do not have to worry about an array going out of bounds etc, so that saves some code. Documentation on .some can be found here
var productList = [{id: 'text3'}, {id: 'text2'}, {id: 'text4', product: 'Shampoo'}]; // Example of selected products
var theDatabaseList = [{id: 'text1'}, {id: 'text2'},{id: 'text3'},{id:'text4', product: 'shampoo'}];
var objectsFound = [];
for(let objectNumber in productList){
var currentId = productList[objectNumber].id;
if (theDatabaseList.some(obj => obj.id === currentId)) {
// Do what you need to do with the matching value here
objectsFound.push(currentId);
}
}
console.log(objectsFound);
An alternative way I compare one object to another is to use a nested for loop with Object.keys().length to get the amount of objects in the array. Code below:
var productList = [{id: 'text3'}, {id: 'text2'}, {id: 'text4', product: 'Shampoo'}]; // Example of selected products
var theDatabaseList = [{id: 'text1'}, {id: 'text2'},{id: 'text3'},{id:'text4', product: 'shampoo'}];
var objectsFound = [];
for(var i = 0; i < Object.keys(productList).length; i++){
for(var j = 0; j < Object.keys(theDatabaseList).length; j++){
if(productList[i].id === theDatabaseList[j].id){
objectsFound.push(productList[i].id);
}
}
}
console.log(objectsFound);
To answer your exact question, if are just searching for a value in an object, you can use a single for in loop.
var vendors = [
{
Name: 'Magenic',
ID: 'ABC'
},
{
Name: 'Microsoft',
ID: 'DEF'
}
];
for(var ojectNumbers in vendors){
if(vendors[ojectNumbers].Name === 'Magenic'){
console.log('object contains Magenic');
}
}
Alternatively you can do:
const find = (key, needle) => return !!~vendors.findIndex(v => (v[key] === needle));
var without2 = (arr, args) => arr.filter(v => v.id !== args.id);
Example:
without2([{id:1},{id:1},{id:2}],{id:2})
Result:
without2([{id:1},{id:1},{id:2}],{id:2})
You can try this its work for me.
const _ = require('lodash');
var arr = [
{
name: 'Jack',
id: 1
},
{
name: 'Gabriel',
id: 2
},
{
name: 'John',
id: 3
}
]
function findValue(arr,value) {
return _.filter(arr, function (object) {
return object['name'].toLowerCase().indexOf(value.toLowerCase()) >= 0;
});
}
console.log(findValue(arr,'jack'))
//[ { name: 'Jack', id: 1 } ]
const a = [{one:2},{two:2},{two:4}]
const b = a.filter(val => "two" in val).length;
if (b) {
...
}
I would rather go with regex.
If your code is as follows,
vendors = [
{
Name: 'Magenic',
ID: 'ABC'
},
{
Name: 'Microsoft',
ID: 'DEF'
}
];
I would recommend
/"Name":"Magenic"/.test(JSON.stringify(vendors))
let array = [{
name: 'first'
}, {
name: 'd'
}, {
name: 'cc'
}, {
name: 'bbb'
}, {
name: 'aaaa'
}]
let firstElement = array.shift()
// sort array by item name's length:
array.sort((a, b) => {
return b.name.length - a.name.length
})
array.unshift(firstElement)
console.log(array)
I'm currently using this code, althought I believe that I could get rid of firstElement's .shift() and later on .unshift() by having this logic implemented in the array.sort()'s function so I wouldn't have to create an additional array. I have tried several answers found on here but none have worked so far for my use case.
You can do check in sort() method for non-first element:
let array = [{
name: 'first'
}, {
name: 'd'
}, {
name: 'cc'
}, {
name: 'bbb'
}, {
name: 'aaaa'
}]
array.sort((a, b) => {
if (a !== array[0] && b !== array[0]) { // Check if there are not first element
return b.name.length - a.name.length
}
})
Doing this using the sort function alone is actually impossible, at least in the general case of an array containing arbitrary data. Comparing the values passed to the sort function to the first element as done in this answer fails if the element contains multiple copies of the first element for example:
let x = {name:'first'};
let array = [x,{name:'d'},{name:'cc'},{name:'bbb'},x,{name:'aaaa'}];
array.sort((a, b) => {
if (a !== array[0] && b !== array[0]) { // Check if there are not first element
return b.name.length - a.name.length
}
});
console.log(array);
It may work in your case since you seem to have an array of objects without duplicate elements, but for the more general case you'd have to compare indices, not elements - which is not possible using .sort, by design. The comparator function should generally only compare elements by their values and not anything else.
I'd generally just stick with what you're already got; the performance difference is going to be minimal at most, and it won't be prone to breaking if you decide to add duplicates in your array or introduce other types one day.
I have an array of objects that I'm trying to loop through to match for a specific value, if found delete that object else return false. Below is the code:
array: [{
obj1:{
id: null,
name:'test',
address: '6857346jfhbdjshb'
},
obj12:{
id: 678346,
name:'test',
address: '63784hgj'
},
obj13:{
id: null,
name:'test',
address: 'tevhgvd'
},
obj15:{
id: 65847,
name:'test',
address: 'djhvwe677ghdgv'
},
obj18:{
address: ""
}
}]
js:
for (var obj in array){
if (array[obj].address === "63784hgj" || array[obj].address === "djhvwe677ghdgv" ||array[prop].address === "")
{
array[obj].destroy(); //equivalent to array[1].destroy() (destroy, delete,remove,hide, pop none of them work)
}
}
I'm not sure which function is the correct one to remove object from array.
You apparently want to filter out certain properties from the single element of your array, which is an object, containing subobjects, when the address property of the subobject matches one or more string values.
Extract the first element of the array, then loop over its properties with a for...in loop. If the subproperty matches, delete the property with delete.
function filterproc(array) {
var o = array[0];
for (var k in o)
if (o[k].address === "....")
delete o[k];
}
To match against multiple possibilities, consider using indexOf, which checks if an array contains some value:
if (['63784hgj', ...].indexOf(o[k]) !== -1) ...
If what you want is what toranaburo described in his answer then nothing to do with mine. :( (inform me to delete mine)
If you want a function which returns the new value do this:
var forbiddenAddressList = ['', '63784hgj', 'djhvwe677ghdgv'];
var newArray = myArray.filter(i => forbiddenAddressList.indexof(i.address) === -1);
another way:
var newArray = [];
for (var i = 0; i < myArray.length; i++)
if(forbiddenAddressList.indexof(i.address) === -1)
newArray.push(myArray[i]);
So if what you're asking is to loop through an array of objects, and if the value of a property is found then delete the object it belongs to, then this is what I came up with.
var array = [
{id: null,name:'test',address: '6857346jfhbdjshb'},
{id: 678346,name:'test',address: '63784hgj'},
{id: null,name:'test',address: 'tevhgvd'},
{id: 65847,name:'test',address: 'djhvwe677ghdgv'},
{address: ""}
];
for (var obj in array){
if (array[obj].address === "63784hgj" || array[obj].address === "djhvwe677ghdgv" || array[obj].address === "")
{
array.splice(obj, 1);
}
}
I modified your array of objects, but everything except Obj1, Obj2 etc. remains because arrays are already indexed, thus array[0] refers to Obj1. Also in your if statement you had array[prop] which is undefined, so be sure to change it in your code. This worked for what I think you were trying to do, so let me know if it helps.
Given a state like this:
state = {
things: [
{ id: 'a1', name: 'thing 1' },
{ id: 'a2', name: 'thing 2' },
],
};
How can I create a new state where ID "a1" is removed? It's easy enough to push new items:
return state.set(state.get('things').push(newThing));
But I can't figure out how to search for and remove an object by its id property. I tried this:
return state.set('tracks',
state.get('tracks').delete(
state.get('tracks').findIndex(x => x.get('id') === 'a2')
)
)
But it seems messy, plus it only works if the item is found, because if findIndex returns -1, that's a valid value for delete.
You can use Array#filter.
return state.set('things', state.get('things').filter(o => o.get('id') !== 'a1'));
When you are using filter it iterates all cycle -> one effective way is finding index => slice and using splitter ...
const index = state.findIndex(data => data.id === action.id);
return [...state.slice(0, index), ...state.slice(index + 1)];
Alternatively, as you are "searching and then deleting"...
var itemIndex = this.state.get("tracks").findIndex(x => x.get('id') === 'a2');
return itemIndex > -1 ? this.state.deleteIn(["tracks", itemIndex]) : this.state;
This will ensure the state is not mutated when there are no changes.
Found this thread while looking for a solution to a similar task.
Solved it with update method:
return state.update('things', (things) => things.filter((t) => t.id !== action.things.id))
any idea/comment which one is better/preferred?
You can do that even without immutable.js with following function.
function arrayFilter(array, filter) {
let ret = array
let removed = 0
for (let index = 0; index < array.length; index++) {
const passed = filter(array[index], index, array)
if (!passed) {
ret = [...ret.slice(0, index - removed), ...ret.slice(index - removed + 1)]
removed++
}
}
return ret
}
ImmutableJS working with nested arrays
Immutablejs is great but at the same time makes things more complicated in some edge cases, particularly when working with nested arrays.
Sometimes it is easier to take it back to JS in a general sense for this particular issue.
// 1. get a copy of the list into normal JavaScript
const myList = state.getIn(['root', 'someMap', 'myList']).toJS()
// 2. remove item in list using normal JavaScript and/or anything else
myList.splice(deleteIndex, 1)
// 3. return the new state based on mutated myList
return state
.mergeDeep({ root: { someMap: { myList: undefined } }})
.mergeDeep({ root: { someMap: { myList } }})
Unfortunately, step 3 is necessary to specifically set to undefined because if you simply set myList directly as an array value, ImmutableJS will do a comparison of values between the current list and only modify them creating strange behavior.
The justification for this is to simplify the mental overhead. I do not recommend doing this in a loop, rather manipulate the pure JS array in a loop if you must but should be prior to step 3.
My code
var arr = ['a','b',1];
var results = arr.map(function(item){
if(typeof item ==='string'){return item;}
});
This gives the following results
["a","b",undefined]
I don't want undefined in the results array. How can I do it?
You aren't returning anything in the case that the item is not a string. In that case, the function returns undefined, what you are seeing in the result.
The map function is used to map one value to another, but it looks like you actually want to filter the array, which a map function is not suitable for.
What you actually want is a filter function. It takes a function that returns true or false based on whether you want the item in the resulting array or not.
var arr = ['a','b',1];
var results = arr.filter(function(item){
return typeof item ==='string';
});
Filter works for this specific case where the items are not modified. But in many cases when you use map you want to make some modification to the items passed.
if that is your intent, you can use reduce:
var arr = ['a','b',1];
var results = arr.reduce((results, item) => {
if (typeof item === 'string') results.push(modify(item)) // modify is a fictitious function that would apply some change to the items in the array
return results
}, [])
Since ES6 filter supports pointy arrow notation (like LINQ):
So it can be boiled down to following one-liner.
['a','b',1].filter(item => typeof item ==='string');
You can implement like a below logic.
Suppose you want an array of values.
let test = [ {name:'test',lastname:'kumar',age:30},
{name:'test',lastname:'kumar',age:30},
{name:'test3',lastname:'kumar',age:47},
{name:'test',lastname:'kumar',age:28},
{name:'test4',lastname:'kumar',age:30},
{name:'test',lastname:'kumar',age:29}]
let result1 = test.map(element =>
{
if (element.age === 30)
{
return element.lastname;
}
}).filter(notUndefined => notUndefined !== undefined);
output : ['kumar','kumar','kumar']
My solution would be to use filter after the map.
This should support every JS data type.
example:
const notUndefined = anyValue => typeof anyValue !== 'undefined'
const noUndefinedList = someList
.map(// mapping condition)
.filter(notUndefined); // by doing this,
//you can ensure what's returned is not undefined
You only return a value if the current element is a string. Perhaps assigning an empty string otherwise will suffice:
var arr = ['a','b',1];
var results = arr.map(function(item){
return (typeof item ==='string') ? item : '';
});
Of course, if you want to filter any non-string elements, you shouldn't use map(). Rather, you should look into using the filter() function.
If you have to use map to return custom output, you can still combine it with filter.
const arr = ['a','b',1]
const result = arr.map(element => {
if(typeof element === 'string')
return element + ' something'
}).filter(Boolean) // this will filter out null and undefined
console.log(result) // output: ['a something', 'b something']
var arr = ['a','b',1];
var results = arr.filter(function(item){
if (typeof item ==='string') {return item;}
});
If you use it like this, your problem will be solved.
Also, you will have a clean and short code
var _ = require('lodash'); //but first, npm i lodash --save
var arr = ['a','b',1];
var results = _.compact(
_.map(arr, function(item){
if(_.isString(item)){return item;}
}
); //false, null, undefined ... etc will not be included
with ES6...
const _ = require('lodash'); //but first, npm i lodash --save
const arr = ['a','b',1];
const results = _.compact(
_.map(arr, item => {
if(_.isString(item)){return item;}
}
);
I run into this quite frequently where the type after filtering will still be string | number. So, to expand upon these solutions and include type safety you can use a user-defined type guard.
https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates
const result = ['a','b',1].filter((item) => typeof item ==='string');
// result is typed as (string | number)[]
Better type safety using user-defined type guard
const result = ['a','b',1].filter((item): item is string => typeof item ==='string');
// result is now typed as string[]
The problem:
the issue is arr.map() will do a full iteration of arr array length, i.e. map() method will loop as much as the length of arr is, no matter what condition you have inside it, so if you defined a condition inside it e.g. if(typeof item ==='string'){return item;} even if the condition is not happening, the map() will be forced to keep looping until finishing the looping of the whole arr so it will give you undefined for the rest of elements if the condition is not met.
The solutions:
Solution One: if you want to return the whole item in the array when the condition is met, you can use arr.filter() so the filter will return the whole item for the iteration e.g. if you have array of objects like bellow
const arr = [{name: "Name1", age: 25}, {name: "Name2", age: 30}, {name: "Name3", age: 25}]
and you want to return the whole objects when the condition is met like example below
const filteredItems = arr.filter((item)=>{if(item.age === 25){return true}})
console.log(filteredItems) //results: [{name: "Name1", age: 25}, {name: "Name3", age: 25}]
conclusion: filter() method returns an array of the whole items in it if the condition is met.
Solution Two: if you want to return only a specific data of the objects (or the whole object or any shape of data) in array i.e. if you want to return only the names in array without the ages, you can do this
const namesOnly = arr.map((item)=>{if(item.age === 25){return item.name}})
console.log(namesOnly) //results: ["Name1, udefined, "Name3"]
now to remove the undefined you just use filter() method on the results like below
const namesOnly = arr.map((item)=>{if(item.age === 25){return item.name}}).filter((item)=> !!item)
console.log(namesOnly) //results: ["Name1, "Name3"]
conclusion: map() method returns an array of specifically defined data in the return, and returns undefined if the condition is not met. so then we can use filter() method to remove the undefined.
You can filter records with .map easily using below example code
const datapoints = [
{
PL_STATUS: 'Packetloss',
inner_outerx: 'INNER',
KPI_PL: '97.9619'
},
{
PL_STATUS: 'Packetloss',
inner_outerx: 'OUTER',
KPI_PL: '98.4621',
},
{
PL_STATUS: 'Packetloss',
inner_outerx: 'INNER',
KPI_PL: '97.8770',
},
{
PL_STATUS: 'Packetloss',
inner_outerx: 'OUTER',
KPI_PL: '97.5674',
},
{
PL_STATUS: 'Packetloss',
inner_outerx: 'INNER',
KPI_PL: '98.7150',
},
{
PL_STATUS: 'Packetloss',
inner_outerx: 'OUTER',
KPI_PL: '98.8969'
}
];
const kpi_packetloss_inner: string[] = [];
datapoints.map((item: { PL_STATUS: string; inner_outerx: string; KPI_PL: string }) => {
if (item.PL_STATUS === 'Packetloss' && item.inner_outerx === 'INNER') {
kpi_packetloss_inner.push(item.KPI_PL);
}
})
console.log(kpi_packetloss_inner);
Map is used when you want to produced new modified array from the original array.
the simple answer may be for someone
var arr = ['a','b',1];
var results = arr.filter(function(item){
// Modify your original array here
return typeof item ==='string';
}).filter(a => a);