<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Programming | Kate Gable</title>
	<atom:link href="https://www.katesky.com/category/programming/feed/" rel="self" type="application/rss+xml" />
	<link>https://www.katesky.com</link>
	<description>sharing knowledge, encouraging to learn, promoting passion for coding, supporting mothers who code</description>
	<lastBuildDate>Mon, 09 Dec 2024 19:58:07 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.8.3</generator>
<site xmlns="com-wordpress:feed-additions:1">193364748</site>	<item>
		<title>Harnessing Angular 19’s Resource API: A Declarative Approach to Data Management</title>
		<link>https://www.katesky.com/2024/12/07/harnessing-angular-19s-resource-api-a-declarative-approach-to-data-management/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=harnessing-angular-19s-resource-api-a-declarative-approach-to-data-management</link>
		
		<dc:creator><![CDATA[Katerina Gable]]></dc:creator>
		<pubDate>Sat, 07 Dec 2024 06:13:07 +0000</pubDate>
				<category><![CDATA[angular]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Programming]]></category>
		<guid isPermaLink="false">https://www.katesky.com/?p=290</guid>

					<description><![CDATA[<p>Introducing resource Angular 19 brings an exciting addition to its toolkit: the Resource API. This API is designed to simplify asynchronous data fetching and state management, making it more declarative and easier to integrate into Angular’s reactive ecosystem. In this blog, we’ll <br /><a href="https://www.katesky.com/2024/12/07/harnessing-angular-19s-resource-api-a-declarative-approach-to-data-management/" class="more-link">Read More</a></p>
The post <a href="https://www.katesky.com/2024/12/07/harnessing-angular-19s-resource-api-a-declarative-approach-to-data-management/">Harnessing Angular 19’s Resource API: A Declarative Approach to Data Management</a> first appeared on <a href="https://www.katesky.com">Kate Gable</a>.]]></description>
										<content:encoded><![CDATA[<body>
<p><strong>Introducing resource</strong></p>



<p>Angular 19 brings an exciting addition to its toolkit: the <strong>Resource API</strong>. This API is designed to simplify asynchronous data fetching and state management, making it more declarative and easier to integrate into Angular’s reactive ecosystem.</p>



<p>In this blog, we’ll explore:</p>



<ul class="wp-block-list">
<li>The benefits of the Resource API</li>



<li>How it compares to traditional <code>HttpClient</code> implementations</li>



<li>A complete example using <strong>products</strong> data, showcasing filtering by category with <code>linkedSignal</code></li>
</ul>



<h2 class="wp-block-heading"><strong>What is the Resource API?</strong></h2>



<p>The Resource API leverages Angular’s reactivity model to provide:</p>



<ul class="wp-block-list">
<li><strong>Declarative data fetching</strong>: Define and manage resources with minimal boilerplate.</li>



<li><strong>Automatic state management</strong>: Built-in handling of loading, errors, and data updates.</li>



<li><strong>Reactive signals</strong>: Seamless synchronization with Angular’s <code>signal</code> and <code>linkedSignal</code>.</li>
</ul>



<h2 class="wp-block-heading"><strong>How Does It Compare to the Traditional Approach?</strong></h2>



<h3 class="wp-block-heading"><strong>The Old Way</strong></h3>



<p>In pre-Angular 19 applications, data was often fetched using <code>HttpClient</code> within services, requiring manual state management. Here’s an example:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: jscript; title: ; notranslate">
// Old service implementation
getProducts(): Observable&lt;Product[]&gt; {
  return this.http.get&lt;Product[]&gt;('https://api.example.com/products');
}

// Old component implementation
this.productService.getProducts().subscribe({
  next: (data) =&gt; { this.products = data; this.isLoading = false; },
  error: (err) =&gt; { this.error = err.message; this.isLoading = false; }
});

</pre></div>


<h4 class="wp-block-heading"><strong>Drawbacks</strong></h4>



<ol class="wp-block-list">
<li><strong>Manual State Management</strong>: Developers had to handle loading, errors, and data updates manually in every component.</li>



<li><strong>Boilerplate Code</strong>: Each service and component required repetitive code for fetching data and managing states.</li>



<li><strong>Complexity with Derived States</strong>: Filtering and transforming data often required separate streams or additional logic.</li>



<li><strong>Inconsistent Practices</strong>: Different developers might manage states differently, leading to inconsistent patterns across the codebase.</li>
</ol>



<h3 class="wp-block-heading"><strong>The New Way with Resource API</strong></h3>



<p>With the Resource API, the repetitive parts of state management are handled automatically:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: jscript; title: ; notranslate">
products = resource({
  loader: async () =&gt; {
    const response = await fetch('https://api.example.com/products');
    if (!response.ok) {
      throw new Error('Failed to fetch products');
    }
    return response.json();
  },
});

</pre></div>


<h4 class="wp-block-heading"><strong>Why It’s Better Long Term</strong></h4>



<ol class="wp-block-list">
<li><strong>Declarative Syntax</strong>: The Resource API makes data fetching and state management part of the Angular reactivity model. Developers define what data they need and how it should react to changes, and Angular handles the rest.</li>



<li><strong>Built-In State Management</strong>: Automatic handling of loading, error, and data states simplifies component logic.</li>



<li><strong>Derived State with Signals</strong>: The seamless integration with <code>linkedSignal</code> allows for effortless creation of derived states (e.g., filtering products by category).</li>



<li><strong>Reduced Boilerplate</strong>: Say goodbye to repetitive loading/error handling code in every component.</li>



<li><strong>Consistency</strong>: Provides a standard way to manage data across the application, making it easier to onboard new developers or refactor code.</li>



<li><strong>Future-Ready</strong>: The Resource API aligns with Angular’s long-term strategy of reactive, signal-based development, ensuring compatibility and smoother upgrades in the future.</li>
</ol>



<hr class="wp-block-separator has-alpha-channel-opacity">



<h2 class="wp-block-heading"><strong>Building a Product List with the Resource API</strong></h2>



<p>Let’s dive into a practical example: fetching and displaying products with filtering by category.</p>



<h3 class="wp-block-heading"><strong>Service Implementation</strong></h3>



<p>Here’s how to set up the Resource API in your <code>ProductService</code>:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: plain; title: ; notranslate">
import { Injectable, signal, resource } from '@angular/core';
import { Product, Response } from './Product';

@Injectable({
  providedIn: 'root',
})
export class ProductService {
  private apiUrl = 'https://dummyjson.com/products';

  // Signal to trigger the resource loader
  private trigger = signal&amp;lt;void&gt;(undefined);

  // Resource to fetch products
  products = resource({
    request: () =&gt; this.trigger,
    loader: async () =&gt; {
      const response = await fetch(this.apiUrl);
      if (!response.ok) {
        throw new Error('Failed to fetch products');
      }
      const data = response.json() as Promise&amp;lt;Response&gt;;
      return (await data).products;
    },
  });

  // Method to reload products
  reload() {
    this.trigger.set(undefined);
  }
}

</pre></div>


<h3 class="wp-block-heading"><strong>Component with Linked Signals</strong></h3>



<p>In the component, <code>linkedSignal</code> is used to manage derived states, like the list of categories and filtered products.</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: jscript; title: ; notranslate">
import { Component, effect, linkedSignal, signal } from '@angular/core';
import { ProductService } from '../product.service';

@Component({
  selector: 'app-product-list',
  templateUrl: './product-list.component.html',
  styleUrls: ['./product-list.component.css'],
})
export class ProductListComponent {
  productsResource = this.productService.products;
  selectedCategory = signal&lt;string&gt;('all');

  categories = linkedSignal(() =&gt; {
    if (!this.productsResource.value()) return [];
    return Array.from(
      new Set(
        this.productsResource.value()?.map((product) =&gt; product.category)
      )
    );
  });

  filteredProducts = linkedSignal(() =&gt; {
    const category = this.selectedCategory();
    if (category === 'all') return this.productsResource.value();
    return this.productsResource.value()?.filter(
      (product) =&gt; product.category === category
    );
  });

  constructor(private productService: ProductService) {}

  selectCategory(e: any) {
    this.selectedCategory.set(e.target.value);
  }

  reload() {
    this.selectedCategory.set('all');
    this.productService.reload();
  }
}

</pre></div>


<h3 class="wp-block-heading"><strong>The Benefits in Action</strong></h3>



<ol class="wp-block-list">
<li><strong>Automatic State Management</strong>: Loading, data, and error states are built into the Resource API.</li>



<li><strong>Simplified UI Logic</strong>: The use of <code>linkedSignal</code> ensures that the UI automatically updates when data or user selections change.</li>



<li><strong>Consistency Across Features</strong>: The same declarative pattern can be used for other data resources, ensuring uniformity across the app.</li>
</ol>



<hr class="wp-block-separator has-alpha-channel-opacity">



<h2 class="wp-block-heading"><strong>Conclusion</strong></h2>



<p>Angular 19’s Resource API is a significant step forward for Angular developers. By combining declarative data fetching with reactive signals, it provides:</p>



<ul class="wp-block-list">
<li>Cleaner code</li>



<li>Enhanced maintainability</li>



<li>A more consistent developer experience</li>
</ul>



<p>When compared to the traditional approach, the Resource API not only reduces boilerplate but also aligns with Angular’s vision for reactive, signal-driven development, ensuring its relevance for years to come.</p>



<p>If you’re still using the old way, now is the time to embrace the future with Angular 19. What do you think about the Resource API? Let’s discuss in the comments below!</p>



<p>Checkout complete code example here:  <a href="https://github.com/kategable/stackblitz-starters-linkedSignal" target="_blank" rel="noopener" title="">https://github.com/kategable/stackblitz-starters-linkedSignal</a></p>



<p>and StackBlitz: <a href="https://stackblitz.com/~/github.com/kategable/stackblitz-starters-linkedSignal" target="_blank" rel="noopener" title="">https://stackblitz.com/~/</a><a href="https://stackblitz.com/~/github.com/kategable/stackblitz-starters-linkedSignal?file=src/app/demo-r/product-list.component.ts" target="_blank" rel="noopener" title="">github.com/kategable/stackblitz-starters-linkedSignal</a></p>



<p>get more Angularv19 here <a href="https://blog.angular.dev/meet-angular-v19-7b29dfd05b84" target="_blank" rel="noopener" title="">https://blog.angular.dev/meet-angular-v19-7b29dfd05b84</a></p>



<p></p>
</body>The post <a href="https://www.katesky.com/2024/12/07/harnessing-angular-19s-resource-api-a-declarative-approach-to-data-management/">Harnessing Angular 19’s Resource API: A Declarative Approach to Data Management</a> first appeared on <a href="https://www.katesky.com">Kate Gable</a>.]]></content:encoded>
					
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">290</post-id>	</item>
		<item>
		<title>Dynamic Filtering with Angular&#8217;s linkedSignal v19</title>
		<link>https://www.katesky.com/2024/12/05/dynamic-filtering-with-angulars-linkedsignal-v19/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=dynamic-filtering-with-angulars-linkedsignal-v19</link>
		
		<dc:creator><![CDATA[Katerina Gable]]></dc:creator>
		<pubDate>Thu, 05 Dec 2024 19:02:33 +0000</pubDate>
				<category><![CDATA[angular]]></category>
		<category><![CDATA[Programming]]></category>
		<guid isPermaLink="false">https://www.katesky.com/?p=283</guid>

					<description><![CDATA[<p>Exploring Angular’s linkedSignal: Enhancing Signal Reusability In Angular applications, managing state and reactivity often involves tools like BehaviorSubject from RxJS. With the advent of signals, particularly linkedSignal, Angular provides a declarative and more Angular-native approach to handling dynamic state transformations. Let’s build <br /><a href="https://www.katesky.com/2024/12/05/dynamic-filtering-with-angulars-linkedsignal-v19/" class="more-link">Read More</a></p>
The post <a href="https://www.katesky.com/2024/12/05/dynamic-filtering-with-angulars-linkedsignal-v19/">Dynamic Filtering with Angular’s linkedSignal v19</a> first appeared on <a href="https://www.katesky.com">Kate Gable</a>.]]></description>
										<content:encoded><![CDATA[<body>
<p><strong>Exploring Angular’s <code>linkedSignal</code>: Enhancing Signal Reusability</strong></p>



<p>In Angular applications, managing state and reactivity often involves tools like <code>BehaviorSubject</code> from RxJS. With the advent of signals, particularly <code>linkedSignal</code>, Angular provides a declarative and more Angular-native approach to handling dynamic state transformations.</p>



<p>Let’s build a product filtering example to see how <code>linkedSignal</code> can simplify state management and potentially replace <code>BehaviorSubject</code>.</p>



<p>In this post, we’ll explore what <code>linkedSignal</code> is, its benefits, how it can replace <code>BehaviorSubject</code> in many use cases, and how you can implement it in your Angular applications.</p>



<hr class="wp-block-separator has-alpha-channel-opacity">



<h3 class="wp-block-heading"><strong>What is <code>linkedSignal</code>?</strong></h3>



<p>The <code>linkedSignal</code> function allows you to create a signal whose value is derived from other existing signals. Unlike computed signals that focus on recalculating values reactively, <code>linkedSignal</code> is more tailored for situations where the new signal’s lifecycle and reactivity are closely tied to another signal or context.</p>



<p>This makes <code>linkedSignal</code> a perfect choice when:</p>



<ul class="wp-block-list">
<li>You need to extend or transform the behavior of an existing signal.</li>



<li>You want to maintain a scoped reactive context within your application.</li>
</ul>



<h3 class="wp-block-heading"><strong>Why Replace <code>BehaviorSubject</code> with Signals?</strong></h3>



<p>Traditionally, Angular developers have relied on <code>BehaviorSubject</code> from RxJS for state management, such as holding and propagating reactive data. While powerful, <code>BehaviorSubject</code> has limitations that <code>linkedSignal</code> can address:</p>



<h4 class="wp-block-heading"><strong>1. Boilerplate Reduction</strong></h4>



<p>With <code>BehaviorSubject</code>, you often have to write additional boilerplate for initialization, subscriptions, and updates:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: jscript; title: ; notranslate">
const subject = new BehaviorSubject&lt;number&gt;(0);
subject.next(5);
subject.subscribe(value =&gt; console.log(value));
</pre></div>


<p>In contrast, <code>linkedSignal</code> provides a more concise and declarative API:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: jscript; title: ; notranslate">
const baseSignal = signal(0);
const linked = linkedSignal(() =&gt; baseSignal() * 2);
console.log(linked());

</pre></div>


<h4 class="wp-block-heading"><strong>2. Declarative State Management</strong></h4>



<p><code>linkedSignal</code> eliminates the need for manual subscription management, reducing the risk of memory leaks and simplifying code structure. It’s purely declarative, meaning dependencies and updates are handled automatically.</p>



<h4 class="wp-block-heading"><strong>3. Tight Integration with Angular</strong></h4>



<p>Unlike <code>BehaviorSubject</code>, which is an external library feature, <code>linkedSignal</code> is natively supported in Angular, ensuring seamless integration with other Angular features like templates and change detection.</p>



<h4 class="wp-block-heading"><strong>Scenario: Product Filtering</strong></h4>



<p>Imagine you have a list of products, and the user can filter them by category. Using <code>linkedSignal</code>, we can create a reactive filtered list that updates automatically whenever the category or product list changes.</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: jscript; title: ; notranslate">
import { Component, signal, linkedSignal } from '@angular/core';

@Component({
  selector: 'app-product-filter',
  standalone: true,
  template: `
    &lt;h2&gt;Product Filter&lt;/h2&gt;
    &lt;div&gt;
      &lt;label&gt;Filter by Category:&lt;/label&gt;
      &lt;select [value]="selectedCategory()" (change)="selectCategory($event.target.value)"&gt;
        &lt;option value="all"&gt;All&lt;/option&gt;
        &lt;option *ngFor="let category of categories" [value]="category"&gt;
          {{ category }}
        &lt;/option&gt;
      &lt;/select&gt;
    &lt;/div&gt;

    &lt;div&gt;
      &lt;h3&gt;Products&lt;/h3&gt;
      &lt;ul&gt;
        &lt;li *ngFor="let product of filteredProducts()"&gt;
          {{ product.name }} - {{ product.category }}
        &lt;/li&gt;
      &lt;/ul&gt;
    &lt;/div&gt;
  `,
})
export class ProductFilterComponent {
  // Base signal for the list of products
  products = signal([
    { name: 'Laptop', category: 'Electronics' },
    { name: 'Headphones', category: 'Electronics' },
    { name: 'Sofa', category: 'Furniture' },
    { name: 'Table', category: 'Furniture' },
    { name: 'T-shirt', category: 'Clothing' },
  ]);

  // Signal for selected category
  selectedCategory = signal&lt;string&gt;('all');

  // Derived signal for filtering products based on the selected category
  filteredProducts = linkedSignal(() =&gt; {
    const category = this.selectedCategory();
    const allProducts = this.products();
    return category === 'all'
      ? allProducts
      : allProducts.filter(product =&gt; product.category === category);
  });

  // Generate a list of unique categories from the products
  get categories() {
    return Array.from(new Set(this.products().map(product =&gt; product.category)));
  }

  // Update the selected category
  selectCategory(category: string) {
    this.selectedCategory.set(category);
  }
}

</pre></div>


<hr class="wp-block-separator has-alpha-channel-opacity">



<h4 class="wp-block-heading"><strong>Component Code</strong></h4>



<hr class="wp-block-separator has-alpha-channel-opacity">



<p><a href="https://stackblitz.com/~/github.com/kategable/stackblitz-starters-linkedSignal?file=src/app/demo/demo.component.ts" target="_blank" rel="noopener" title="">https://stackblitz.com/~/github.com/kategable/stackblitz-starters-linkedSignal?file=src/app/demo/demo.component.ts</a></p>



<h4 class="wp-block-heading"><strong>How It Works</strong></h4>



<ol class="wp-block-list">
<li><strong>Signal Initialization</strong>:
<ul class="wp-block-list">
<li><code>products</code> contains a static list of products.</li>



<li><code>selectedCategory</code> holds the currently selected category.</li>
</ul>
</li>



<li><strong>Linked Signal</strong>:
<ul class="wp-block-list">
<li><code>filteredProducts</code> derives its value based on <code>products</code> and <code>selectedCategory</code>. It automatically recalculates when either signal changes.</li>
</ul>
</li>



<li><strong>Reactivity in Action</strong>:
<ul class="wp-block-list">
<li>When the user selects a category, the <code>filteredProducts</code> signal updates the displayed list of products dynamically.</li>
</ul>
</li>



<li>If we used <code><strong>BehaviorSubject</strong></code>:
<ul class="wp-block-list">
<li>Set up a subject, </li>



<li>add pipe for transformations, </li>



<li>add manual subscriptions or async pipe. </li>
</ul>
</li>



<li>With <code><strong>linkedSignal</strong></code>:
<ul class="wp-block-list">
<li>Avoid subscriptions entirely.</li>



<li>Use Angular’s built-in reactivity for value updates.</li>



<li>Keep the code cleaner and more concise.</li>
</ul>
</li>
</ol>



<hr class="wp-block-separator has-alpha-channel-opacity">



<h4 class="wp-block-heading"><strong>Benefits of This Approach</strong></h4>



<ol class="wp-block-list">
<li><strong>Dynamic Updates</strong>: Any change in the product list or selected category immediately updates the filtered list.</li>



<li><strong>Code Clarity</strong>: The filtering logic is encapsulated within the <code>linkedSignal</code>, making it reusable and easier to test.</li>



<li><strong>Performance</strong>: Signals ensure efficient updates with minimal recalculations.</li>
</ol>



<hr class="wp-block-separator has-alpha-channel-opacity">



<h3 class="wp-block-heading"><strong>When to Use <code>linkedSignal</code> Instead of <code>BehaviorSubject</code></strong></h3>



<p>Consider using <code>linkedSignal</code> when:</p>



<ul class="wp-block-list">
<li>You are managing state within Angular components or services.</li>



<li>You want a simpler, Angular-native alternative to RxJS subjects.</li>



<li>The logic requires automatic dependency tracking and updates.</li>
</ul>



<p>However, if you’re managing streams from external sources (e.g., WebSocket connections or complex asynchronous workflows), <code>BehaviorSubject</code> or other RxJS operators may still be more appropriate.</p>



<p></p>



<h3 class="wp-block-heading"><strong>Conclusion</strong></h3>



<p>Angular’s <code>linkedSignal</code> simplifies state management by allowing you to derive signals dynamically. This product filter example demonstrates how you can build responsive and dynamic applications with ease.</p>



<p>Give it a try in your next Angular project, and let me know if you want more examples or use cases!</p>



<p>Code link:</p>



<p>git clone <a href="https://github.com/kategable/stackblitz-starters-linkedSignal.git" target="_blank" rel="noopener" title="">https://github.com/kategable/stackblitz-starters-linkedSignal.git</a></p>



<p>stackblitz – <a href="https://stackblitz.com/~/github.com/kategable/stackblitz-starters-linkedSignal?file=src/app/demo/demo.component.ts" target="_blank" rel="noopener" title="">https://stackblitz.com/~/github.com/kategable/stackblitz-starters-linkedSignal?file=src/app/demo/demo.component.ts</a></p>



<p>get more Angularv19 here <a href="https://blog.angular.dev/meet-angular-v19-7b29dfd05b84" target="_blank" rel="noopener" title="">https://blog.angular.dev/meet-angular-v19-7b29dfd05b84</a></p>
</body>The post <a href="https://www.katesky.com/2024/12/05/dynamic-filtering-with-angulars-linkedsignal-v19/">Dynamic Filtering with Angular’s linkedSignal v19</a> first appeared on <a href="https://www.katesky.com">Kate Gable</a>.]]></content:encoded>
					
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">283</post-id>	</item>
		<item>
		<title>Nested arrays, arrays with nested dolls as an example</title>
		<link>https://www.katesky.com/2022/12/21/nested-arrays-arrays-with-nested-dolls-as-an-example/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=nested-arrays-arrays-with-nested-dolls-as-an-example</link>
					<comments>https://www.katesky.com/2022/12/21/nested-arrays-arrays-with-nested-dolls-as-an-example/#comments</comments>
		
		<dc:creator><![CDATA[Katerina Gable]]></dc:creator>
		<pubDate>Wed, 21 Dec 2022 02:09:30 +0000</pubDate>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Programming]]></category>
		<guid isPermaLink="false">https://www.katesky.com/?p=266</guid>

					<description><![CDATA[<p>This is my attempt to help a new developer understand how nested arrays opperate. A nested array can be thought of like a set of nested dolls, where each doll is contained within another doll. This array can be thought of as <br /><a href="https://www.katesky.com/2022/12/21/nested-arrays-arrays-with-nested-dolls-as-an-example/" class="more-link">Read More</a></p>
The post <a href="https://www.katesky.com/2022/12/21/nested-arrays-arrays-with-nested-dolls-as-an-example/">Nested arrays, arrays with nested dolls as an example</a> first appeared on <a href="https://www.katesky.com">Kate Gable</a>.]]></description>
										<content:encoded><![CDATA[<body>
<p>This is my attempt to help a new developer understand how nested arrays opperate.</p>



<p>A nested array can be thought of like a set of nested dolls, where each doll is contained within another doll.</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: jscript; title: ; notranslate">
[
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9]
]

</pre></div>


<p>This array can be thought of as a set of three nested dolls, where the first doll contains the array <code>[1, 2, 3]</code>, the second doll contains the array <code>[4, 5, 6]</code>, and the third doll contains the array <code>[7, 8, 9]</code>.</p>



<p>Each of these inner arrays is itself an array, and so we can think of them as smaller dolls contained within the larger dolls. For example, the first doll (which contains the array <code>[1, 2, 3]</code>) can be thought of as containing three smaller dolls, one for each element in the array.</p>



<p>We can continue this process of nesting to any level. For example, we could have an array like this:</p>



<p>For example, consider the following array:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: jscript; title: ; notranslate">
[
  [
    [1, 2],
    [3, 4]
  ],
  [
    [5, 6],
    [7, 8]
  ]
]

</pre></div>


<p>This array can be thought of as a set of two nested dolls, where the first doll contains the array <code>[[1, 2], [3, 4]]</code> and the second doll contains the array <code>[[5, 6], [7, 8]]</code>. Each of these inner arrays is itself an array, and so we can think of them as smaller dolls contained within the larger dolls. The innermost arrays (<code>[1, 2]</code> and <code>[3, 4]</code>) can be thought of as the smallest dolls in the set.</p>



<p>Here is an example of how you can search for elements within an array in JavaScript:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: jscript; title: ; notranslate">
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9];

// Search for the number 3 in the array
const index = numbers.indexOf(3);
console.log(index);  // Output: 2 (the index of 3 in the array)

// Search for the number 10 in the array
const index = numbers.indexOf(10);
console.log(index);  // Output: -1 (10 is not in the array)

</pre></div>


<p>In this example, we have an array of numbers called <code>numbers</code>. We use the <code>indexOf()</code> method to search for the number <code>3</code> in the array. This method returns the index of the element in the array, or <code>-1</code> if the element is not found.</p>



<p>So, when we search for the number <code>3</code>, the <code>indexOf()</code> method returns <code>2</code>, which is the index of <code>3</code> in the <code>numbers</code> array. When we search for the number <code>10</code>, the <code>indexOf()</code> method returns <code>-1</code>, indicating that <code>10</code> is not in the array.</p>



<p>There are also other ways to search for elements within an array in JavaScript. For example, you can use the <code>includes()</code> method to check if an element is present in an array:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: jscript; title: ; notranslate">
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9];

// Check if the array includes the number 3
const includesThree = numbers.includes(3);
console.log(includesThree);  // Output: true

// Check if the array includes the number 10
const includesTen = numbers.includes(10);
console.log(includesTen);  // Output: false

</pre></div>


<p>Here is an example of how you can search for elements within a nested array in JavaScript:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: jscript; title: ; notranslate">
const numbers = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];

// Search for the number 3 in the nested array
for (const innerArray of numbers) {
  const index = innerArray.indexOf(3);
  if (index !== -1) {
    console.log(`Found 3 at index ${index} of inner array ${innerArray}`);
  }
}

// Output: "Found 3 at index 2 of inner array [1, 2, 3]"

</pre></div>


<p>In this example, we have a nested array called <code>numbers</code>, which contains three inner arrays: <code>[1, 2, 3]</code>, <code>[4, 5, 6]</code>, and <code>[7, 8, 9]</code>. We use a <code>for...of</code> loop to iterate over each of the inner arrays, and we use the <code>indexOf()</code> method to search for the number <code>3</code> within each inner array.</p>



<p>If the <code>indexOf()</code> method returns a value other than <code>-1</code>, it means that <code>3</code> was found within the inner array. In this case, we log a message indicating the index at which <code>3</code> was found and the inner array in which it was found.</p>



<p>You can use a similar approach to search for elements within nested arrays at any level of nesting. For example, you could use a nested loop to iterate over each element within each inner array, and so on.</p>



<p>Here is an example of how you can use a recursive function to search for an element within a nested array in JavaScript:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: jscript; title: ; notranslate">
function findElement(element, array) {
  for (const item of array) {
    if (Array.isArray(item)) {
      // If the current item is an array, recursively search for the element within that array
      const result = findElement(element, item);
      if (result) {
        // If the element was found, return the result
        return result;
      }
    } else if (item === element) {
      // If the current item is the element we are searching for, return its index
      return array.indexOf(item);
    }
  }

  // If the element was not found, return null
  return null;
}

const numbers = [[1, 2, 3], [4, 5, [6, 7]], [8, 9]];

// Search for the number 7 in the nested array
const index = findElement(7, numbers);
console.log(index);  // Output: "Found 7 at index [1, 1, 1]"

</pre></div>


<p>In this example, we have defined a function called <code>findElement()</code> that takes an element and an array as arguments. The function uses a <code>for...of</code> loop to iterate over the elements in the array, and it checks whether each element is itself an array.</p>



<p>If the element is an array, the function calls itself recursively with the element and the array as arguments. This process continues until an element is found that is not an array, at which point the function checks whether the element is the element we are searching for. If it is, the function returns the index of the element within the array. If the element is not found, the function returns <code>null</code>.</p>



<p>In the example above, we use the <code>findElement()</code> function to search for the number <code>7</code> within the nested array <code>numbers</code>. The function returns <code>[1, 1, 1]</code>, which indicates that <code>7</code> was found at index <code>1</code> within the second inner array, which is itself at index <code>1</code> within the <code>numbers</code> array.</p>



<p>Here is an example of how you can use the <code>flat()</code> method to flatten a nested array and search for an element within it using the <code>indexOf()</code> method, which can provide a faster search for large arrays:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: jscript; title: ; notranslate">
const numbers = [[1, 2, 3], [4, 5, [6, 7]], [8, 9]];

// Flatten the nested array using the flat() method
const flatNumbers = numbers.flat();

// Search for the number 7 in the flattened array
const index = flatNumbers.indexOf(7);
console.log(index);  // Output: 5 (the index of 7 in the flattened array)

</pre></div>


<p>In this example, we have a nested array called <code>numbers</code> that contains three inner arrays: <code>[1, 2, 3]</code>, <code>[4, 5, [6, 7]]</code>, and <code>[8, 9]</code>. We use the <code>flat()</code> method to flatten the array and create a new, one-dimensional array called <code>flatNumbers</code>.</p>



<p>We can then use the <code>indexOf()</code> method to search for the number <code>7</code> within the flattened array. This method returns the index of the element in the array, or <code>-1</code> if the element is not found. In this case, the method returns <code>5</code>, which is the index of <code>7</code> in the flattened array.</p>



<p>Using the <code>flat()</code> method and the <code>indexOf()</code> method can provide a faster search for large arrays, as the <code>flat()</code> method flattens the array in place and the <code>indexOf()</code> method performs a linear search through the array.</p>



<p>It is important to use optimal algorithm for searching nested arrays.</p>



<p>Using an optimal algorithm for searching nested arrays is important because it can help to reduce the time and computational resources required to find an element within the array. This can be particularly important when working with large arrays, as the time and resources required to search the array can increase significantly with the size of the array.</p>



<p>There are several algorithms that can be used to search nested arrays, each with its own trade-offs in terms of efficiency and complexity. For example, a linear search through the array (such as using the <code>indexOf()</code> method) can be relatively simple to implement, but it may not be the most efficient option for large arrays. On the other hand, more complex algorithms, such as binary search, can be more efficient but may require more implementation effort.</p>



<p>It is generally a good idea to choose an algorithm that is both efficient and easy to implement, depending on the specific requirements of your application. For example, if you are working with a small array that does not need to be searched frequently, a simple linear search may be sufficient. However, if you are working with a large array that needs to be searched frequently, you may want to consider using a more efficient algorithm.</p>



<pre class="wp-block-preformatted"></pre>



<pre class="wp-block-preformatted"></pre>
</body>The post <a href="https://www.katesky.com/2022/12/21/nested-arrays-arrays-with-nested-dolls-as-an-example/">Nested arrays, arrays with nested dolls as an example</a> first appeared on <a href="https://www.katesky.com">Kate Gable</a>.]]></content:encoded>
					
					<wfw:commentRss>https://www.katesky.com/2022/12/21/nested-arrays-arrays-with-nested-dolls-as-an-example/feed/</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">266</post-id>	</item>
	</channel>
</rss>
