Discovering values within an array of objects through the use of JavaScript

Consider the following:

let myArray = [
  { 
    id: "3283267",
    innerArray: ["434","6565","343","3665"]
  },
  {
    id: "9747439",
    innerArray: ["3434","38493","4308403840","34343"]
  },
  {
    id: "0849374",
    innerArray: ["343434","57575","389843","38493"]
  }
];

If I want to search for the presence of the string "38493" in the innerArray of objects within myArray, and then create a new array containing the corresponding ids, it would look something like this:

let arrayWithIds = ["9747439", "0849374"];

Answer №1

Here's a straightforward approach using the Array.forEach and Array.indexOf methods:

let searchItem =  "38493", 
    foundItems = [];

myArray.forEach(item => {
     if (item.innerArray.indexOf(searchItem) !== -1) {
         this.push(item.id);   
     }
}, foundItems);

console.log(foundItems);  // ["9747439", "0849374"]

Answer №2

To extract ids from your array after filtering based on a specific condition, you can use ES6 syntax:

const filteredArrayWithIds = myArray
  .filter(item => item.subArray.includes('38493'))
  .map(item => item.id)

Alternatively, here is the ES5 version:

var filteredArrayWithIds = myArray
  .filter(function(item) {
    return ~item.innerArray.indexOf('38493');
  })
  .map(function(item) {
    return item.id;
  })

Answer №3

If you're looking for an ES5 way to achieve this, you can also try the following method.

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);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Reserve Your Room in Style with C++!

Seeking assistance with the Hotel Bookings Problem C++ from InterviewBit website. I've been struggling to find a solution to this particular question. The scenario is as follows: A hotel manager needs to process N advance bookings for rooms for an upc ...

Resampling a MATLAB uint8 array is a common practice in data processing

After importing a .JPG file into the Matlab workspace, the software interpreted it as a 2D array measuring 300x300 with unsigned integers ranging from 0 to 255. My objective is to analyze a specific row within this matrix. To achieve this, I simply isolate ...

Guide to writing a Jasmine test case to verify Toggle class behavior within a click event

My directive is responsible for toggling classes on an element, and it's working as expected. However, I seem to be encountering an issue with the jasmine test case for it. // Code for toggling class fileSearch.directive('toggleClass', func ...

Sending documents via ExpressJS

I'm currently developing a small application using the latest NodeJS and ExpressJS, but I've encountered an issue with uploading files. My routes are set up like this: app.get('/Share', share.index); app.post('/Share/Process&apos ...

Dealing with alternating rows in a dynamic manner: tips and tricks

Exploring an example scenario: (view live demonstration) Sample HTML structure: <div class="wrapper"> <div city_id="1" class="odd">Street Name #1 in city 1</div> <div city_id="3" class="even">Street Name #2 in city 3</d ...

Display a popup notification when clicking in Angular 2

Can anyone help me with displaying a popup message when I click on the select button that says "you have selected this event"? I am using Angular 2. <button type="button" class="button event-buttons" [disabled]="!owned" style=""(click)="eventSet()"&g ...

Problems with Navbar rendering on multiple occasions

GENERAL INFO I've encountered an issue with the re-rendering of my sidemenu in Gatsby. Despite my efforts, I can't prevent the sidemenu from re-rendering and overriding the data that I set for it. const [activeParent, setActiveParent] = useState ...

The inputs for Node express middleware are unclear and lack definition

I am currently exploring Node.js as a potential replacement for my existing DOT NET API. I have created middleware to enforce basic non-role authorization in my application, but I am encountering compilation problems with the function inputs. Compilation ...

Tips for extracting a value from a geojson response using a specific key

When analyzing the geojson response below, I am trying to access the following: Type and Segments To achieve this, I attempted the following: return data["type"] //does not work, error received return data["features"][0]["properties"]["segments"] ...

Utilizing a SQL LIKE operator within a SELECT statement with Twitter/typeahead.js

Here is the code that I am working with: $places = query("SELECT * FROM places WHERE postal_code = ? or place_name = ? or admin_code1 = ? or admin_name2 = ? or admin_name1 = ?", $_GET["geo"],$_GET["geo"],$_GET["geo"],$_GET["geo"],$_GET["geo"]); When I st ...

Is it possible to configure Lambda NodeJS 12.x flags (like --experimental-modules) when using AWS SAM local start-api?

When setting up my nodejs server, I chose to use ES6 module syntax: package.json "type": "module" So far, running my server locally as a nodejs process has been successful. For example: "scripts": { "dev": "npm outdated ; nodemon --experimental-modul ...

Mastering the syntax of Babel in Node.js

Hey there! I've encountered a syntax issue while migrating to babel. The problem lies in importing an unnamed module. In traditional Node.js default import, it's possible to import without specifying the module name and passing in the app. Howeve ...

SwipeJS is not compatible with a JQuery-Mobile web application

I am currently attempting to integrate SwipeJS (www.swipejs.com) into my JQuery-Mobile website. <script src="bin/js/swipe.js"></script> <style> /* Swipe 2 required styles */ .swipe { overflow: hidden; ...

Releasing the mouse button after dragging successfully without the use of any libraries

I have implemented a pure CSS snap scroll feature and now I need to determine the position of an element in relation to the viewport once the user stops dragging. However, I prefer not to rely on any complex libraries as I do not require any actual movemen ...

Retrieving Angular URL Parameters Containing Slashes

I'm currently in the process of developing a single page angular application. This app retrieves a token from the URL and then sends it to an API. At the moment, my URL structure is as follows: www.example.com/?token=3d2b9bc55a85b641ce867edaac8a9791 ...

Looking to set a cursor style on a table row with JavaScript?

let table = document.getElementById(TABLE_NAME); let nextRow = table.tBodies[0].rows.length; row.setAttribute('style', "cursor: pointer;"); I am trying to implement a double click event on a table row, which is working as expected in most ...

How can I combine three dynamic dropdown menus into a single dynamic multi-level dropdown using PHP and Javascript?

Hello everyone, I've created a three-level dynamic dropdown menu that includes categories, subcategories, and questions. Each category has a corresponding subcategory, and each subcategory has corresponding questions. Below is the code for this functi ...

Generating JButtons on the fly along with attaching addActionListener and then parsing JSON to retrieve a

Trying to automate the population of actionListener for buttons, but encountering an error at jObject = jArray.getJSONObject(i) when the generator() function returns a JSONArray. Additionally, aiming to change buttons[i] = new JButton("pfdfs"); to buttons ...

Ways to identify the visible elements on a webpage using JavaScript

I'm working on a nextjs app , I am looking to dynamically update the active button in the navbar based on which section is currently visible on the page. The child elements of the page are structured like this: <div id="section1" > < ...

Issue encountered while attempting to deactivate button until numerical data is entered in the OTP field using Vuejs

otp_value: '', isFadeout: false, verifyOtp() { this.disabled = true; this.otpBtnClicked = false; this.verified = true; }, <input class="o ...