Given the following:
var myArray = [
{
id: "3283267",
innerArray: ["434","6565","343","3665"]
},
{
id: "9747439",
innerArray: ["3434","38493","4308403840","34343"]
},
{
id: "0849374",
innerArray: ["343434","57575","389843","38493"]
}
];
How would I search the objects inside myArray to determine if the string "38493" is present in the innerArray and then return a new array with the id of the object....like such:
var arrayWithIds = ["9747439", "0849374"];
asked Nov 9, 2016 at 22:07
3 Answers 3
Simple solution using Array.forEach
and Array.indexOf
functions:
var search = "38493",
result = [];
myArray.forEach(function(o) {
if (o.innerArray.indexOf(search) !== -1) this.push(o.id);
}, result);
console.log(result); // ["9747439", "0849374"]
answered Nov 9, 2016 at 22:14
Sign up to request clarification or add additional context in comments.
Comments
You can filter your array and then map ids (using ES6 syntax):
const arrayWithIds = myArray
.filter(a => a.innerArray.includes('38493'))
.map(a => a.id)
Here is ES5 alternative:
var arrayWithIds = myArray
.filter(function(a) {
return ~a.innerArray.indexOf('38493');
})
.map(function(a) {
return a.id;
})
answered Nov 9, 2016 at 22:09
1 Comment
webbydevy
Unfortunately, I have to use ES5.
ES5 way, you may also do as follows.
var myArray = [
{
id: "3283267",
innerArray: ["434","6565","343","3665"]
},
{
id: "9747439",
innerArray: ["3434","38493","4308403840","34343"]
},
{
id: "0849374",
innerArray: ["343434","57575","389843","38493"]
}
],
searchData = "38493",
result = myArray.reduce(function(p,c){
return ~c.innerArray.indexOf(searchData) ? (p.push(c.id),p) : p;
},[]);
console.log(result);
answered Nov 10, 2016 at 9:45
Comments
lang-js
currentElement.innerArray.indexOf("38493")
to tell if the string is in the array and pushescurrentElement.id
onto the result array.