How to check if array of object contains a string [duplicate] - javascript

This question already has answers here:
How to determine if Javascript array contains an object with an attribute that equals a given value?
(27 answers)
Closed 3 years ago.
let's say I have an array of objects:
let arr = [
{
name: 'Jack',
id: 1
},
{
name: 'Gabriel',
id: 2
},
{
name: 'John',
id: 3
}
]
I need to check whether that array includes the name 'Jack' for example using:
if (arr.includes('Jack')) {
// don't add name to arr
} else {
// push name into the arr
}
but arr.includes('Jack') returns false, how can I check if an array of objects includes the name?

Since you need to check the object property value in the array, you can try with Array​.prototype​.some():
The some() method tests whether at least one element in the array passes the test implemented by the provided function. It returns a Boolean value.
let arr = [
{
name: 'Jack',
id: 1
},
{
name: 'Gabriel',
id: 2
},
{
name: 'John',
id: 3
}
]
var r = arr.some(i => i.name.includes('Jack'));
console.log(r);

Related

Check if an array of object is exactly equal to another array that contains one of its property [duplicate]

This question already has answers here:
Check if an array contains any element of another array in JavaScript
(32 answers)
Closed 1 year ago.
I have these 2 arrays
The first one is fixed and does not change and contains the id of the 2nd array:
fixed=["123","456","789"]
The second can change
variableArray=[{name:"Joe",id:"123"},{name:"Joe",id:"456"},{name:"Joe",id:"789"}]
I want to return true if, even if there were some changes at the end the variable array is the same length and contains exactly the same keys of the "fixed"
NOT VALID:
fixed=["123","456","789"]
variableArray=[{name:"Joe",id:"456"},{name:"Joe",id:"789"}]
return false because is missing the id "123" (and the length is also different so is excluded by default)
NOT VALID:
fixed=["123","456","789"]
variableArray=[{name:"Joe",id:"123"},{name:"Joe",id:"456"},{name:"Joe",id:"001"}]
this will return false because, even if contains 3 elements as there are in the "fixed" is missing the id "789" and have another "001" instead
as #mplungjan mentiond, you can use Every:
let fixed = ["123", "456", "789"];
let variableArray1 = [{
name: "Joe",
id: "123"
}, {
name: "Joe",
id: "456"
}, {
name: "Joe",
id: "789"
}];
let variableArray2 = [{
name: "Joe",
id: "123"
}, {
name: "Joe",
id: "456"
}, {
name: "Joe",
id: "001"
}]
let containsAll1 = variableArray1.every(elem => fixed.includes(elem.id));
let containsAll2 = variableArray2.every(elem => fixed.includes(elem.id));
console.log(containsAll1, containsAll2);

Why does pushing this object into my array give me a number? [duplicate]

This question already has answers here:
Why does Array.prototype.push return the new length instead of something more useful?
(6 answers)
javascript push returning number instead of object [duplicate]
(1 answer)
Pushing objects in an array only returns last object pushed
(5 answers)
How to use Array.push and return the pushed item?
(3 answers)
Closed 2 years ago.
So, I was building a simple rest api on node, I fixed the problem, but I was just curious as to why I even get a number 4 to begin with? You'll know what I mean when you look at the code, It's just a small snippet of code that I'm confused about.
main.js
const people = [
{ id: 1, firstName: "Daniel"},
{ id: 2, firstName: "Erika" },
{ id: 3, firstName: "Christian"},
];
let person = people.push({ id: people.length + 1, firstName: "Mark"})
If I console.log(person) I get 4 as a value. I mean I understand that If I console.log(people) I will get what I added, but I'm just curious as to why when I console.log(person) I get a value of 4?
Ciao, as #VLAZ said, Array.push returns the new length of your people array.
If you want to get the last person inserted in people array you could do:
const people = [
{ id: 1, firstName: "Daniel"},
{ id: 2, firstName: "Erika" },
{ id: 3, firstName: "Christian"},
];
let person = people[people.push({ id: people.length + 1, firstName: "Mark"}) - 1];
console.log(person)
-1 because the 4th element of the array is the object in position 3

Assert sorted array of objects [duplicate]

This question already has an answer here:
Map and Sort in one iteration in Javascript?
(1 answer)
Closed 4 years ago.
I'm doing unit testing using javascript testing framework (mocha, chai, etc). How can I assert my array of objects using its name?
I can successfully sort this using localeCompare but I'm not getting what I wanted on my test. It just returns 1 or -1.
Here's my a sample of what I want to sort.
var Stuffs = [
{ name: "PWE", address: "1234567890" },
{ name: "NSA", address: "1234567890" },
{ name: "AVE", address: "1234567890" },
{ name: "QRE", address: "1234567890" },
]
How can I assert this to ["AVE", "NSA", "PWE", "QRE"] ?
To get your desired Array, you can use:
Stuffs.map(({ name }) => name).sort();
You could also use reduce() method of array and then sort().
DEMO
var Stuffs = [{ name: "PWE", address: "1234567890" },
{ name: "NSA", address: "1234567890" },
{ name: "AVE", address: "1234567890" },
{ name: "QRE", address: "1234567890" }];
let sortedArr = Stuffs.reduce((r,{name})=>r.concat(name),[]).sort((a,b)=>a.localeCompare(b));
console.log(sortedArr);
Using chai
assert.deepInclude(Stuffs, {name: "AVE"});
assert.deepInclude(Stuffs, {name: "NSA"});
assert.deepInclude(Stuffs, {name: "QRE"});
assert.deepInclude(Stuffs, {name: "PWE"});
Edit: I may have misunderstood it to mean, how can assert that the array has those values.
First you would need a sorted array to compare it to. The original array needs to be cloned (shallow is fine for this) since sort will modify the array it is called on. Using from to generate the clone, we can then alphabetically sort the new array to get the desired order.
const sortedStuffs = Array.from(stuffs).sort(({name: a}, {name: b}) => a.localeCompare(b));
Finally using every, we can compare the names for each element to see if they match. As soon as one fails, the returned value will be false
stuffs.every(({name}, i) => name === sortedStuffs[i].name);
Full working example:
const stuffs = [
{name: "PWE", address: "1234567890"},
{name: "NSA", address: "1234567890"},
{name: "AVE", address: "1234567890"},
{name: "QRE", address: "1234567890"}
];
const sortedStuffs = Array.from(stuffs).sort(({name: a}, {name: b}) => a.localeCompare(b));
const isSorted = stuffs.every(({name}, i) => name === sortedStuffs[i].name);
console.log(isSorted);

How to get Index of an object from an array [JavaScript]? [duplicate]

This question already has answers here:
indexOf method in an object array?
(29 answers)
Closed 5 years ago.
let database = [{
name: 'James Bond',
code: '007'
},
{
name: 'El',
code: '11'
}
]
let subject = {
name: 'James Bond',
code: '007'
}
database.indexOf(subject)
This returns -1. I found similar questions here on SO but they were all mostly asking to find index of the object by comparing it to a key value pair.
From DOCS
The indexOf() method returns the index within the calling String
object of the first occurrence of the specified value, starting the
search at fromIndex. Returns -1 if the value is not found.
Use findIndex
DEMO
let database = [{
name: 'James Bond',
code: '007'
},
{
name: 'El',
code: '11'
}
]
let subject = {
name: 'James Bond',
code: '007'
}
console.log(database.findIndex(x => x.name=="James Bond"))
let subInd ;
database.forEach(function(ele,index){
if(ele.name == subject.name && ele.code == subject.code ){
subInd=index;
}
});
console.log(subInd);

Get value by property from javascript object list [duplicate]

This question already has answers here:
how to access object property using variable [duplicate]
(2 answers)
Closed 8 years ago.
i want to get property value from javascript object list, i have a list
var cars = [{ id: 1, name: 'Audi' }, { id: 2, name: 'BMW' }, { id: 1, name: 'Honda' }];
Now i want get id or name property value by using for loop like this
var cars = [{ id: 1, name: 'Audi' }, { id: 2, name: 'BMW' }, { id: 1, name: 'Honda' }];
var items=[];
var firstProp='id';
for (var i = 0; i < model.length; i++) {
//original work
items.push({ value: model[i].firstProp});//here is the problem
}
please give good advise, thanks.
If I understand your problem correctly, you should use square bracket notation instead of dot notation:
//..
items.push({ value: model[i][firstProp]});//here is the problem
You should do like this
items.push({ value: model[i][firstProp]});
the . notation expects the firstProp to be present as a key in dictionary, since the firstProp is a variable that contains a string you should use [] notation.

Categories

Resources