1

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
1
  • Write a loop that uses currentElement.innerArray.indexOf("38493") to tell if the string is in the array and pushes currentElement.id onto the result array. Commented Nov 9, 2016 at 22:09

3 Answers 3

4

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

4

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

Unfortunately, I have to use ES5.
0

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

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.