How to return an object from an array in JavaScript
Create a function that takes an array of people objects and returns the first found astronaut object from the array.
This is the code that I have created;
function findFirstAstronaut(people) {
for (let i = 0; i < people.length; i++) {
if (people.astronaut[i] === false) {
return null
}
else if (people.astronaut[i]) {
return people[i]
}
}
My code is run against this test;
describe("findFirstAstronaut", () => {
it("returns null if no Astronaut is in the array", () => {
expect(findFirstAstronaut()).to.be.null;
});
it("returns a person object who is an astronaut", () => {
const astronaut = { name: "Tim Peake", isAstronaut: true };
expect(findFirstAstronaut([astronaut])).to.have.keys([
"name",
"isAstronaut"
]);
expect(findFirstAstronaut([astronaut]).isAstronaut).to.be.true;
});
it("returns the first astronaut from the array", () => {
const astronauts = [
{ name: "Johnny Karate", isAstronaut: false },
{ name: "Neil Armstrong", isAstronaut: true },
{ name: "Valentina Tereshkova", isAstronaut: true },
{ name: "Bert Macklin", isAstronaut: false },
{ name: "Eileen Collins", isAstronaut: true },
{ name: "Kip Hackman", isAstronaut: false }
];
expect(findFirstAstronaut(astronauts)).to.eql({
name: "Neil Armstrong",
isAstronaut: true
});
});
});
How do I fix my code?
javascript arrays loops object
New contributor
add a comment |
Create a function that takes an array of people objects and returns the first found astronaut object from the array.
This is the code that I have created;
function findFirstAstronaut(people) {
for (let i = 0; i < people.length; i++) {
if (people.astronaut[i] === false) {
return null
}
else if (people.astronaut[i]) {
return people[i]
}
}
My code is run against this test;
describe("findFirstAstronaut", () => {
it("returns null if no Astronaut is in the array", () => {
expect(findFirstAstronaut()).to.be.null;
});
it("returns a person object who is an astronaut", () => {
const astronaut = { name: "Tim Peake", isAstronaut: true };
expect(findFirstAstronaut([astronaut])).to.have.keys([
"name",
"isAstronaut"
]);
expect(findFirstAstronaut([astronaut]).isAstronaut).to.be.true;
});
it("returns the first astronaut from the array", () => {
const astronauts = [
{ name: "Johnny Karate", isAstronaut: false },
{ name: "Neil Armstrong", isAstronaut: true },
{ name: "Valentina Tereshkova", isAstronaut: true },
{ name: "Bert Macklin", isAstronaut: false },
{ name: "Eileen Collins", isAstronaut: true },
{ name: "Kip Hackman", isAstronaut: false }
];
expect(findFirstAstronaut(astronauts)).to.eql({
name: "Neil Armstrong",
isAstronaut: true
});
});
});
How do I fix my code?
javascript arrays loops object
New contributor
Is that a particular unit test framework?
– Peter Mortensen
51 mins ago
add a comment |
Create a function that takes an array of people objects and returns the first found astronaut object from the array.
This is the code that I have created;
function findFirstAstronaut(people) {
for (let i = 0; i < people.length; i++) {
if (people.astronaut[i] === false) {
return null
}
else if (people.astronaut[i]) {
return people[i]
}
}
My code is run against this test;
describe("findFirstAstronaut", () => {
it("returns null if no Astronaut is in the array", () => {
expect(findFirstAstronaut()).to.be.null;
});
it("returns a person object who is an astronaut", () => {
const astronaut = { name: "Tim Peake", isAstronaut: true };
expect(findFirstAstronaut([astronaut])).to.have.keys([
"name",
"isAstronaut"
]);
expect(findFirstAstronaut([astronaut]).isAstronaut).to.be.true;
});
it("returns the first astronaut from the array", () => {
const astronauts = [
{ name: "Johnny Karate", isAstronaut: false },
{ name: "Neil Armstrong", isAstronaut: true },
{ name: "Valentina Tereshkova", isAstronaut: true },
{ name: "Bert Macklin", isAstronaut: false },
{ name: "Eileen Collins", isAstronaut: true },
{ name: "Kip Hackman", isAstronaut: false }
];
expect(findFirstAstronaut(astronauts)).to.eql({
name: "Neil Armstrong",
isAstronaut: true
});
});
});
How do I fix my code?
javascript arrays loops object
New contributor
Create a function that takes an array of people objects and returns the first found astronaut object from the array.
This is the code that I have created;
function findFirstAstronaut(people) {
for (let i = 0; i < people.length; i++) {
if (people.astronaut[i] === false) {
return null
}
else if (people.astronaut[i]) {
return people[i]
}
}
My code is run against this test;
describe("findFirstAstronaut", () => {
it("returns null if no Astronaut is in the array", () => {
expect(findFirstAstronaut()).to.be.null;
});
it("returns a person object who is an astronaut", () => {
const astronaut = { name: "Tim Peake", isAstronaut: true };
expect(findFirstAstronaut([astronaut])).to.have.keys([
"name",
"isAstronaut"
]);
expect(findFirstAstronaut([astronaut]).isAstronaut).to.be.true;
});
it("returns the first astronaut from the array", () => {
const astronauts = [
{ name: "Johnny Karate", isAstronaut: false },
{ name: "Neil Armstrong", isAstronaut: true },
{ name: "Valentina Tereshkova", isAstronaut: true },
{ name: "Bert Macklin", isAstronaut: false },
{ name: "Eileen Collins", isAstronaut: true },
{ name: "Kip Hackman", isAstronaut: false }
];
expect(findFirstAstronaut(astronauts)).to.eql({
name: "Neil Armstrong",
isAstronaut: true
});
});
});
How do I fix my code?
javascript arrays loops object
javascript arrays loops object
New contributor
New contributor
edited 52 mins ago
Peter Mortensen
13.4k1983111
13.4k1983111
New contributor
asked 7 hours ago
Georgia Lumley
1127
1127
New contributor
New contributor
Is that a particular unit test framework?
– Peter Mortensen
51 mins ago
add a comment |
Is that a particular unit test framework?
– Peter Mortensen
51 mins ago
Is that a particular unit test framework?
– Peter Mortensen
51 mins ago
Is that a particular unit test framework?
– Peter Mortensen
51 mins ago
add a comment |
5 Answers
5
active
oldest
votes
You need to use the index for the array.
people[i] // for the object
people[i].isAstronaut // for a property of the object
Then you need only a check if isAstronaut
is true
and return with the item.
At the end outside of the for
loop, return null
, for a not found astronaut.
If you check inside the loop, you will return too early with the wrong result.
function findFirstAstronaut(people) {
for (let i = 0; i < people.length; i++) {
if (people[i].isAstronaut) {
return people[i];
}
}
return null;
}
add a comment |
ES6 introduces a new way to achieve this, if ES6 is an option for you:
myArray.find(item => {
return item.isAstronaut
})
Or even more abbreviated:
myArray.find(item => item.isAstronaut)
find()
is a one of the new iterators, along with filter()
and map()
and others for more easily working with arrays. find()
will return the first item in your array that matches the condition. The =>
or "arrow function" means that you do not need to explicitly include the return statement.
Read more about ES6 iterators.
add a comment |
You could simply filter out array elements that have an isAstronaut
property equal to false using Array.prototype.filter
. I prefer filter
to Array.prototype.find
since ES6 isn't supported in every browser.
Once you have the filtered array simply take the element in the 0
index position. Something like below:
const astronauts = [{
name: "Johnny Karate",
isAstronaut: false
},
{
name: "Neil Armstrong",
isAstronaut: true
},
{
name: "Valentina Tereshkova",
isAstronaut: true
},
{
name: "Bert Macklin",
isAstronaut: false
},
{
name: "Eileen Collins",
isAstronaut: true
},
{
name: "Kip Hackman",
isAstronaut: false
}
];
//Array destructuring to get the first astronaut:
var [firstAstronautFound] = astronauts.filter(el => el.isAstronaut);
//Line above is same as doing this:
//var firstAstronautFound = astronauts.filter(el => el.isAstronaut)[0];
console.log(firstAstronautFound.name);
add a comment |
First, you may need to check whether there is any item in array or else return null.
Second, you have to check for the property
Third, you have to check for the value of the property isAstronaut
function findFirstAstronaut(people) {
if (people.length > 0)
{
for (let i = 0; i < people.length; i++) {
if (("name" in people[i]) && ("isAstronaut" in people[i])) {
if (people[i].isAstronaut)
return people[i];
else
return true;
}
}
}
else
return null;
}
add a comment |
One liner
arr.filter(item => item.isAstronaut)[0]
New contributor
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Georgia Lumley is a new contributor. Be nice, and check out our Code of Conduct.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53915995%2fhow-to-return-an-object-from-an-array-in-javascript%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
5 Answers
5
active
oldest
votes
5 Answers
5
active
oldest
votes
active
oldest
votes
active
oldest
votes
You need to use the index for the array.
people[i] // for the object
people[i].isAstronaut // for a property of the object
Then you need only a check if isAstronaut
is true
and return with the item.
At the end outside of the for
loop, return null
, for a not found astronaut.
If you check inside the loop, you will return too early with the wrong result.
function findFirstAstronaut(people) {
for (let i = 0; i < people.length; i++) {
if (people[i].isAstronaut) {
return people[i];
}
}
return null;
}
add a comment |
You need to use the index for the array.
people[i] // for the object
people[i].isAstronaut // for a property of the object
Then you need only a check if isAstronaut
is true
and return with the item.
At the end outside of the for
loop, return null
, for a not found astronaut.
If you check inside the loop, you will return too early with the wrong result.
function findFirstAstronaut(people) {
for (let i = 0; i < people.length; i++) {
if (people[i].isAstronaut) {
return people[i];
}
}
return null;
}
add a comment |
You need to use the index for the array.
people[i] // for the object
people[i].isAstronaut // for a property of the object
Then you need only a check if isAstronaut
is true
and return with the item.
At the end outside of the for
loop, return null
, for a not found astronaut.
If you check inside the loop, you will return too early with the wrong result.
function findFirstAstronaut(people) {
for (let i = 0; i < people.length; i++) {
if (people[i].isAstronaut) {
return people[i];
}
}
return null;
}
You need to use the index for the array.
people[i] // for the object
people[i].isAstronaut // for a property of the object
Then you need only a check if isAstronaut
is true
and return with the item.
At the end outside of the for
loop, return null
, for a not found astronaut.
If you check inside the loop, you will return too early with the wrong result.
function findFirstAstronaut(people) {
for (let i = 0; i < people.length; i++) {
if (people[i].isAstronaut) {
return people[i];
}
}
return null;
}
answered 7 hours ago
Nina Scholz
174k1388152
174k1388152
add a comment |
add a comment |
ES6 introduces a new way to achieve this, if ES6 is an option for you:
myArray.find(item => {
return item.isAstronaut
})
Or even more abbreviated:
myArray.find(item => item.isAstronaut)
find()
is a one of the new iterators, along with filter()
and map()
and others for more easily working with arrays. find()
will return the first item in your array that matches the condition. The =>
or "arrow function" means that you do not need to explicitly include the return statement.
Read more about ES6 iterators.
add a comment |
ES6 introduces a new way to achieve this, if ES6 is an option for you:
myArray.find(item => {
return item.isAstronaut
})
Or even more abbreviated:
myArray.find(item => item.isAstronaut)
find()
is a one of the new iterators, along with filter()
and map()
and others for more easily working with arrays. find()
will return the first item in your array that matches the condition. The =>
or "arrow function" means that you do not need to explicitly include the return statement.
Read more about ES6 iterators.
add a comment |
ES6 introduces a new way to achieve this, if ES6 is an option for you:
myArray.find(item => {
return item.isAstronaut
})
Or even more abbreviated:
myArray.find(item => item.isAstronaut)
find()
is a one of the new iterators, along with filter()
and map()
and others for more easily working with arrays. find()
will return the first item in your array that matches the condition. The =>
or "arrow function" means that you do not need to explicitly include the return statement.
Read more about ES6 iterators.
ES6 introduces a new way to achieve this, if ES6 is an option for you:
myArray.find(item => {
return item.isAstronaut
})
Or even more abbreviated:
myArray.find(item => item.isAstronaut)
find()
is a one of the new iterators, along with filter()
and map()
and others for more easily working with arrays. find()
will return the first item in your array that matches the condition. The =>
or "arrow function" means that you do not need to explicitly include the return statement.
Read more about ES6 iterators.
answered 7 hours ago
Toby
4,96242146
4,96242146
add a comment |
add a comment |
You could simply filter out array elements that have an isAstronaut
property equal to false using Array.prototype.filter
. I prefer filter
to Array.prototype.find
since ES6 isn't supported in every browser.
Once you have the filtered array simply take the element in the 0
index position. Something like below:
const astronauts = [{
name: "Johnny Karate",
isAstronaut: false
},
{
name: "Neil Armstrong",
isAstronaut: true
},
{
name: "Valentina Tereshkova",
isAstronaut: true
},
{
name: "Bert Macklin",
isAstronaut: false
},
{
name: "Eileen Collins",
isAstronaut: true
},
{
name: "Kip Hackman",
isAstronaut: false
}
];
//Array destructuring to get the first astronaut:
var [firstAstronautFound] = astronauts.filter(el => el.isAstronaut);
//Line above is same as doing this:
//var firstAstronautFound = astronauts.filter(el => el.isAstronaut)[0];
console.log(firstAstronautFound.name);
add a comment |
You could simply filter out array elements that have an isAstronaut
property equal to false using Array.prototype.filter
. I prefer filter
to Array.prototype.find
since ES6 isn't supported in every browser.
Once you have the filtered array simply take the element in the 0
index position. Something like below:
const astronauts = [{
name: "Johnny Karate",
isAstronaut: false
},
{
name: "Neil Armstrong",
isAstronaut: true
},
{
name: "Valentina Tereshkova",
isAstronaut: true
},
{
name: "Bert Macklin",
isAstronaut: false
},
{
name: "Eileen Collins",
isAstronaut: true
},
{
name: "Kip Hackman",
isAstronaut: false
}
];
//Array destructuring to get the first astronaut:
var [firstAstronautFound] = astronauts.filter(el => el.isAstronaut);
//Line above is same as doing this:
//var firstAstronautFound = astronauts.filter(el => el.isAstronaut)[0];
console.log(firstAstronautFound.name);
add a comment |
You could simply filter out array elements that have an isAstronaut
property equal to false using Array.prototype.filter
. I prefer filter
to Array.prototype.find
since ES6 isn't supported in every browser.
Once you have the filtered array simply take the element in the 0
index position. Something like below:
const astronauts = [{
name: "Johnny Karate",
isAstronaut: false
},
{
name: "Neil Armstrong",
isAstronaut: true
},
{
name: "Valentina Tereshkova",
isAstronaut: true
},
{
name: "Bert Macklin",
isAstronaut: false
},
{
name: "Eileen Collins",
isAstronaut: true
},
{
name: "Kip Hackman",
isAstronaut: false
}
];
//Array destructuring to get the first astronaut:
var [firstAstronautFound] = astronauts.filter(el => el.isAstronaut);
//Line above is same as doing this:
//var firstAstronautFound = astronauts.filter(el => el.isAstronaut)[0];
console.log(firstAstronautFound.name);
You could simply filter out array elements that have an isAstronaut
property equal to false using Array.prototype.filter
. I prefer filter
to Array.prototype.find
since ES6 isn't supported in every browser.
Once you have the filtered array simply take the element in the 0
index position. Something like below:
const astronauts = [{
name: "Johnny Karate",
isAstronaut: false
},
{
name: "Neil Armstrong",
isAstronaut: true
},
{
name: "Valentina Tereshkova",
isAstronaut: true
},
{
name: "Bert Macklin",
isAstronaut: false
},
{
name: "Eileen Collins",
isAstronaut: true
},
{
name: "Kip Hackman",
isAstronaut: false
}
];
//Array destructuring to get the first astronaut:
var [firstAstronautFound] = astronauts.filter(el => el.isAstronaut);
//Line above is same as doing this:
//var firstAstronautFound = astronauts.filter(el => el.isAstronaut)[0];
console.log(firstAstronautFound.name);
const astronauts = [{
name: "Johnny Karate",
isAstronaut: false
},
{
name: "Neil Armstrong",
isAstronaut: true
},
{
name: "Valentina Tereshkova",
isAstronaut: true
},
{
name: "Bert Macklin",
isAstronaut: false
},
{
name: "Eileen Collins",
isAstronaut: true
},
{
name: "Kip Hackman",
isAstronaut: false
}
];
//Array destructuring to get the first astronaut:
var [firstAstronautFound] = astronauts.filter(el => el.isAstronaut);
//Line above is same as doing this:
//var firstAstronautFound = astronauts.filter(el => el.isAstronaut)[0];
console.log(firstAstronautFound.name);
const astronauts = [{
name: "Johnny Karate",
isAstronaut: false
},
{
name: "Neil Armstrong",
isAstronaut: true
},
{
name: "Valentina Tereshkova",
isAstronaut: true
},
{
name: "Bert Macklin",
isAstronaut: false
},
{
name: "Eileen Collins",
isAstronaut: true
},
{
name: "Kip Hackman",
isAstronaut: false
}
];
//Array destructuring to get the first astronaut:
var [firstAstronautFound] = astronauts.filter(el => el.isAstronaut);
//Line above is same as doing this:
//var firstAstronautFound = astronauts.filter(el => el.isAstronaut)[0];
console.log(firstAstronautFound.name);
answered 7 hours ago
tommyO
2,07911325
2,07911325
add a comment |
add a comment |
First, you may need to check whether there is any item in array or else return null.
Second, you have to check for the property
Third, you have to check for the value of the property isAstronaut
function findFirstAstronaut(people) {
if (people.length > 0)
{
for (let i = 0; i < people.length; i++) {
if (("name" in people[i]) && ("isAstronaut" in people[i])) {
if (people[i].isAstronaut)
return people[i];
else
return true;
}
}
}
else
return null;
}
add a comment |
First, you may need to check whether there is any item in array or else return null.
Second, you have to check for the property
Third, you have to check for the value of the property isAstronaut
function findFirstAstronaut(people) {
if (people.length > 0)
{
for (let i = 0; i < people.length; i++) {
if (("name" in people[i]) && ("isAstronaut" in people[i])) {
if (people[i].isAstronaut)
return people[i];
else
return true;
}
}
}
else
return null;
}
add a comment |
First, you may need to check whether there is any item in array or else return null.
Second, you have to check for the property
Third, you have to check for the value of the property isAstronaut
function findFirstAstronaut(people) {
if (people.length > 0)
{
for (let i = 0; i < people.length; i++) {
if (("name" in people[i]) && ("isAstronaut" in people[i])) {
if (people[i].isAstronaut)
return people[i];
else
return true;
}
}
}
else
return null;
}
First, you may need to check whether there is any item in array or else return null.
Second, you have to check for the property
Third, you have to check for the value of the property isAstronaut
function findFirstAstronaut(people) {
if (people.length > 0)
{
for (let i = 0; i < people.length; i++) {
if (("name" in people[i]) && ("isAstronaut" in people[i])) {
if (people[i].isAstronaut)
return people[i];
else
return true;
}
}
}
else
return null;
}
answered 7 hours ago
Sonal Borkar
35719
35719
add a comment |
add a comment |
One liner
arr.filter(item => item.isAstronaut)[0]
New contributor
add a comment |
One liner
arr.filter(item => item.isAstronaut)[0]
New contributor
add a comment |
One liner
arr.filter(item => item.isAstronaut)[0]
New contributor
One liner
arr.filter(item => item.isAstronaut)[0]
New contributor
New contributor
answered 6 hours ago
Ashay Mandwarya
515
515
New contributor
New contributor
add a comment |
add a comment |
Georgia Lumley is a new contributor. Be nice, and check out our Code of Conduct.
Georgia Lumley is a new contributor. Be nice, and check out our Code of Conduct.
Georgia Lumley is a new contributor. Be nice, and check out our Code of Conduct.
Georgia Lumley is a new contributor. Be nice, and check out our Code of Conduct.
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Some of your past answers have not been well-received, and you're in danger of being blocked from answering.
Please pay close attention to the following guidance:
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53915995%2fhow-to-return-an-object-from-an-array-in-javascript%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Is that a particular unit test framework?
– Peter Mortensen
51 mins ago