0

I can't understand the reason of using [0] in front of dish.id and dish.featured in the following code:

import { Injectable } from '@angular/core';
import { Dish } from '../shared/dish';
import { DISHES } from '../shared/dishes';

@Injectable()
export class DishService {

  constructor() { }

  getDishes(): Dish[] {
    return DISHES;
  }

  getDish(id: number): Dish {
    return DISHES.filter((dish) => (dish.id === id))[0];
  }

  getFeaturedDish(): Dish {
    return DISHES.filter((dish) => dish.featured)[0];
  }
}

This is the Dish class:

import { Comment } from './comment';

export class Dish {
    id: number;
    name: string;
    image: string;
    category: string;
    label: string;
    price: string;
    featured: boolean;
    description: string;
    comments: Comment[];
}
Hasani
  • 3,543
  • 14
  • 65
  • 125
  • 2
    "filter(..)" return an array. This array can be empty, can has one value or can has several values, but is an array. with [0] we get the the first element of the array. You can use "find(...)" method not filter to get the first element that is according with the condition – Eliseo May 30 '19 at 16:16
  • 2
    If you have an array `arr`, then `arr[0]` is the first element. This is very basic JS stuff so I'm not sure if there's some other misunderstanding here. – jcalz May 30 '19 at 16:16
  • I'd suggest running some debug code and step through it in your browser's debugger. See what just ` DISHES.filter((dish) => (dish.id === id))` comes up with. Just a guess that filter returns an array. – Dortimer May 30 '19 at 16:17
  • 2
    @Dortimer No need to guess; [the documentation states that it does](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter) :) – Heretic Monkey May 30 '19 at 16:18
  • Related: [How to find first element of array matching a boolean condition in JavaScript?](https://stackoverflow.com/q/10457264/215552), which recommends the use of `find` instead of `filter()[0]`. – Heretic Monkey May 30 '19 at 16:19

2 Answers2

3

Read this .filter(). The reason why the dish.id and dish.featured has [0] in the end because filter always returns the result in an array.

var words = ['a','spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];

const result = words.filter(word => word.length == 1);

console.log(result);
Abdul Basit
  • 1,352
  • 1
  • 10
  • 18
2

Filter returns an array so when you use [0] It means take the first selection. You can read more here: Filter

Nico
  • 1,961
  • 17
  • 20