Limit in Arrays in ECMAScript

Create new Javascript file named product.js. This file contains code demo as below:

class Product {

    constructor(id, name, price, quantity) {
        this.id = id;
        this.name = name;
        this.price = price;
        this.quantity = quantity;
    }

    toString() {
        return 'Id: ' + this.id + '\nName: ' + this.name + '\nPrice: ' + this.price + '\nQuantity: ' + this.quantity;
    }

    total() {
        return this.price * this.quantity;
    }

}

module.exports = Product;




Create new Javascript file named index.js. This file contains code demo as below:

let Product = require('../entities/product');

let product1 = new Product("p01", "name 1", 4, 2);
let product2 = new Product("p02", "name 2", 11, 3);
let product3 = new Product("p03", "name 3", 7, 8);

let products = [product1, product2, product3];

console.log('Use Limit');
products.slice(0, 2)
        .forEach(function (product, index) {
            console.log(product.toString());
            console.log('------------------------');
        });

console.log('Use Limit and Order By');
products.sort((p, q) => p.price - q.price <= 0)
        .slice(0, 2)
        .forEach(function (product, index) {
            console.log(product.toString());
            console.log('------------------------');
        });

console.log('Use Limit and Where and Order By');
products.filter(p => p.price > 2)
        .sort((p, q) => p.price - q.price <= 0)
        .slice(0, 1)
        .forEach(function (product, index) {
            console.log(product.toString());
            console.log('------------------------');
        });

Use node index.js statement run code demo

Use Limit
Id: p01
Name: name 1
Price: 4
Quantity: 2
------------------------
Id: p02
Name: name 2
Price: 11
Quantity: 3
------------------------

Use Limit and Order By
Id: p02
Name: name 2
Price: 11
Quantity: 3
------------------------
Id: p03
Name: name 3
Price: 7
Quantity: 8
------------------------

Use Limit and Where and Order By
Id: p02
Name: name 2
Price: 11
Quantity: 3
------------------------