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
webbydevy
1,2303 gold badges16 silver badges21 bronze badges
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
RomanPerekhrest
93.1k4 gold badges75 silver badges112 bronze badges
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
madox2
52.3k21 gold badges106 silver badges101 bronze badges
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
Redu
26.3k6 gold badges61 silver badges84 bronze badges
Comments
lang-js
currentElement.innerArray.indexOf("38493")to tell if the string is in the array and pushescurrentElement.idonto the result array.