Open In App

Ember.js Ember.NativeArray Class

Last Updated : 10 Jan, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Ember.js is an open-source JavaScript framework used for developing large client-side web applications which are based on Model-View-Controller (MVC) architecture. Ember.js is one of the most widely used front-end application frameworks. It is made to speed up development and increase productivity. Currently, it is utilized by a large number of websites, including Square, Discourse, Groupon, Linked In, Live Nation, Twitch, and Chipotle.

Ember.NativeArray Class: The NativeArray class provides properties that support the MutableArray class and all of its dependent APIs. This enables the native Array to implement them.

Methods: The following is the list of methods for this class:

  • addObject: This method is used to push an object onto the end of the array if the object is not a present array.
  • addObjects: This method is used to add a number of objects to the array.
  • addObserver: This method is used to register an observer for a property.
  • any: This method is used to check if there are any objects in the target that matches the condition laid by the callback function.
  • cacheFor: This method is used to get the cached value for an already computed property if it exists.
  • clear: This method removes all the elements in the array
  • compact: This method is used to make a copy of an array without null and undefined elements.
  • decrementProperty: This method is used to set the value of the property to the current value minus some amount.
  • every: This method is used to check if all objects in the array pass a specific callback function.
  • filter: This method is used to filter objects in the array according to a specific condition.
  • filterBy: This method is used to return an array with just the items with the matched property.
  • find: This method is used to find elements that match the given callback function.
  • findBy: This method is to get the first item with a property matching the passed value.
  • forEach: This method is used to run a function on every item of the array.
  • get: This method is used to retrieve the value of a property from the object.
  • getEach: This method is used to get all values in the array for a given key.
  • getProperties: This method is used to get the value of multiple properties at once.
  • includes: This method is used to check if a given object is present in the array or not.
  • incrementProperty: This method is used to set the value of the property to the current value plus some amount.
  • indexOf: This method is used to find the index of a given object in the array.
  • insertAt: This method is used to insert an object in a specific position in the array.
  • invoke: This method is used to call the passed method on every object in the receiver that implements it.
  • isAny: This method is used to check if for anyone the element in the array the passed property resolves to the desired value or not.
  • isEvery: This method is used to check if, for each element in the array, the passed property resolves to the desired value or not.
  • lastIndexOf: This method is used to find the last index of an object in the array.
  • map: This method is used to map all items in the array with a specific function.
  • mapBy: This method is used to get the value of the named property on all items in the list. 
  • notifyPropertyChange: This method alerts the observer system that a property change has taken place.
  • objectAt: This method is used to retrieve the object at a given index.
  • objectsAt: This method is used to fetch items for the given array of indices.
  • popObject: This method is used to pop objects from an array.
  • pushObject: This method is used to push an object into an array.
  • pushObjects: This method is used to push multiple objects into an array.
  • reduce: This method is used to combine the values of the array into a single value.
  • reject: This method provides a list of all the enumerated elements for which the provided function returns false.
  • rejectBy: This method returns an array containing the objects for which the given key’s value is false.
  • removeAt: This method is used to remove elements on a given index.
  • removeObject: This method removes all instances of the object from the array.
  • removeObjects: This method removes each supplied item from the given array.
  • removeObserver: This method removes any observers you have registered earlier for this object.
  • replace: This method is used to replace some of the elements in the array with the given objects.
  • reverseObjects: This method reverses the elements in the array.
  • set: This method is used to set the key and value to the object.
  • setEach: This method, for each member, sets the value of the named property.
  • setObjects: This method replaces the receiver’s content with the argument’s substance.
  • setProperties: This method sets a number of properties at once.
  • shiftObject: This method shifts nil, if there are no more, or an object from the array’s beginning.
  • slice: This method is used to return a new array that is a portion of the receiver.
  • sortBy: This method is used to sort an array by the specified key.
  • toArray: This method just transforms the object into a real array.
  • toggleProperty: This method is used to set the value of the boolean property to the opposite of its current value.
  • uniq: This method returns a brand-new array with just unique values in it.
  • uniqBy: This method is used to get objects which unique values for the given key.
  • unshiftObject: This method is used to add a single object to the start of the array.
  • unshiftObjects: This method is used to add objects to the front of the array.
  • without: This method gives back a new array without the given value.

Properties: The following is the list of the properties of this class:

  • []: This property is used to get or set the array content.
  • firstObject: This property is used to retrieve the first object of the array.
  • lastObject: This property is used to retrieve the last object of the array.
  • length: This property is used to retrieve the length of the array.

Step 1: To run the following examples you will need to have an ember project with you. To create one, you will need to install ember-cli first. Write the below code in the terminal:

npm install ember-cli

Step 2: Now you can create the project by typing in the following piece of code:

ember new <project-name> --lang en

To start the server, type:

ember serve

Example 1: In this example, I am going to demonstrate the use of the functions: without, toArray, unshiftObject, unshiftObjects, removeAt, objectAt, find, replace and uniq.

 Type the following code to generate the route for this example:

ember generate route party

app/routes/party.js

Javascript




import Route from '@ember/routing/route';
  
export default class PartyRoute extends Route {
    partyItems = [
        'Digital Camera',
        'Jugs, cups & straws',
        'Balloons',
        'Scissors',
        'Cold Drink',
        'Table Confetti',
        'Party Hats',
        'Wine',
        'Napkins',
        'Party Plates',
        'Speakers',
        'Music System',
        'Cups',
    ];
    item;
    itemString;
    itemList;
    start;
    end;
    idx;
    model() {
        return this.partyItems;
    }
    setupController(controller, model) {
        this._super(controller, model);
        controller.set('partyItems', this.partyItems);
        controller.set('item', this.item);
        controller.set('itemString', this.itemString);
        controller.set('itemList', this.itemList);
        controller.set('start', this.start);
        controller.set('end', this.end);
        controller.set('idx', this.idx);
    }
}


app/controllers/party.js

Javascript




import Ember from 'ember';
import {
    without, toArray, unshiftObject, unshiftObjects,
    removeAt, objectAt, find, replace, uniq
}
    from '@ember/array';
  
export default Ember.Controller.extend({
    actions: {
        withoutItem(item) {
            console.log(item)
            let tempItems;
            tempItems = this.partyItems.without(item);
            let str = '';
            for (let i = 0; i < tempItems.length; i++)
                str += tempItems[i] + '\n';
            alert(str);
            this.set('item', '');
        },
        addItems(itemString) {
            this.itemList = itemString.split(',').toArray();
            if (this.itemList.length == 1)
                this.partyItems.unshiftObject(this.itemList[0]);
            else
                this.partyItems.unshiftObjects(this.itemList);
            this.set('itemString', '');
        },
        removeItems(start, end) {
            this.partyItems.removeAt(start, end);
        },
        getObject(idx) {
            alert(`The item at index ${idx} is 
            ${this.partyItems.objectAt(idx)}`);
        },
        findMultipleWordItems() {
            let reqItem = this.partyItems.find((item) =>
                item.split(' ').toArray().length > 1);
            alert(reqItem);
        },
        replaceItem(itemString) {
            this.itemList = itemString.split(',').toArray();
            if (this.itemList.length > this.partyItems.length)
                alert('Error');
            this.partyItems.replace(0, this.itemList.length,
                this.itemList);
        },
        getUniqueItems() {
            let tempItems = this.partyItems.uniq();
            let str = '';
            for (let i = 0; i < tempItems.length; i++)
                str += tempItems[i] + '\n';
            alert(str);
            this.set('item', '');
        },
    },
});


app/template/party.hbs

HTML




{{page-title "Party"}}
<h3>Here is a list of items: </h3>
<ul>
    {{#each @model as |party|}}
        <li>{{party}}</li>
      {{/each}}
</ul>
<br /><br />
<div>
    <label>Enter Item: </label>
      {{input value=this.item}}
</div>
<div>
    <input
        type="button"
        id="remove-item"
        value="Remove Item"
        {{action "withoutItem" this.item}}
      />
</div>
<br /><br />
<div>
    <label>Enter Items: </label>
      {{input value=this.itemString}}
</div>
<div>
    <input
        type="button"
        id="add-item"
        value="Add Items"
        {{action "addItems" this.itemString}}
      />
</div>
<br /><br />
<div>
    <label>Enter Start Index: </label>
      {{input value=this.start}}
</div>
<div>
    <label>Enter End Index: </label>
      {{input value=this.end}}
</div>
<div>
    <input
        type="button"
        id="remove-items"
        value="Remove Items"
        {{action "removeItems" this.start this.end}}
      />
</div>
<br /><br />
<div>
    <label>Enter Index: </label>
      {{input value=this.idx}}
</div>
<div>
    <input
        type="button"
        id="get-item"
        value="Get Item"
        {{action "getObject" this.idx}}
      />
</div>
<br /><br />
<div>
    <label>Enter Items: </label>
      {{input value=this.itemString}}
</div>
<div>
    <input
        type="button"
        id="replace-item"
        value="Replace Items"
        {{action "replaceItem" this.itemString}}
      />
</div>
<br /><br />
<input
    type="button"
      id="get-multiword"
      value="Get Multiword Items!"
      {{action "findMultipleWordItems"}}
/>
<br /><br />
<input
    type="button"
      id="get-unique"
      value="Get Unique Items!"
      {{action "getUniqueItems"}}
/>
{{outlet}}


Output:

Ember.js Ember.NativeArray Class

Ember.js Ember.NativeArray Class

Example 2: In this example, I am going to demonstrate the use of the function popObject to pop items from the array.

Type the following code to generate the route for this example:

ember generate route notepad

app/routes/notepad.js

Javascript




import Route from '@ember/routing/route';
  
export default class NotepadRoute extends Route {
    items = ['Bread', 'Facewash', 'Egg', 'Pen', 'Medicine'];
    model() {
        return this.items;
    }
    setupController(controller, model) {
        this._super(controller, model);
        controller.set('items', this.items);
    }
}


app/controllers/notepad.js

Javascript




import Ember from 'ember';
import { popObject } from '@ember/array';
  
export default Ember.Controller.extend({
    actions: {
        removeItem() {
            if (this.items.length == 0)
                alert('Item List is Empty');
            this.items.popObject();
        }
    }
})


app/template/notepad.hbs

HTML




{{page-title "Notepad"}}
<h2>Your Items</h2>
<ul>
    {{#each @model as |i|}}
        <li>{{i}}</li>
      {{/each}}
</ul>
<br /><br />
<div>
    <input
        type="button"
        id="remove-item"
        value="Remove Item"
        {{action "removeItem"}}
      />
</div>
{{outlet}}


Output:

Ember.js Ember.NativeArray Class

Ember.js Ember.NativeArray Class

Reference: https://api.emberjs.com/ember/release/classes/Ember.NativeArray



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads