JS Arrays: associative, array to string, array of objects. JS: remove array element

Stack data organization and creation of functions with recursive algorithms is a guideline for determining the quality of a programmer's work. A conventional algorithm has never been the best solution in terms of development, debugging, and modification. Only a functionally complete algorithm that provides recursion on distributed data processing can be considered a developing solution.

DOM + JavaScript Features

The page loaded into the browser forms a tree of DOM elements to which JavaScript has direct access.

Here, JS arrays are the simplest objects, in addition to natural functionality, implementing the stack idea (shift / unshift and push / pop). The selection of the first and last element as a special property of the array plays an important role in the formation of data descriptions and algorithms.

JavaScript recursive function

A recursive function in JavaScript can use additional syntax and semantics that are not available in other languages. Anonymous functions make it possible to equip the syntactic constructions of a language with its own functionality.

Events occur on elements of the DOM tree, and their handlers can change. The work of JS code is the parallel execution of many processes, the dynamics of which are determined by the general functionality loaded in the browser, pages and actions of the visitor.

The functionality implemented in the form of methods of objects, in combination with the “distribution” of responsibilities for processing information between the client and the server, reduces the load on the server and simplifies the JS code.

Variables, Arrays, and Objects

Description of the data determines the algorithm for their use. With this formulation, it is true that the data is primary, and vice versa: the algorithm is primary. “You can’t have mercy” - from the same sphere, the decision is made by the one who puts a punctuation mark or does something else.

Natural language has the highest level of freedom:

  • “Expressions of meaning" to those who speak;
  • "Understanding of the meaning" to those who listen.

An “expression of meaning” by one native speaker is not inferior to “freedom of use” by another native speaker.

JavaScript is a programming language. Therefore, there is no freedom and cannot be. Programming is rigid syntactic constructions and exact meaning. Even the condition that the type of a variable can be determined only at the time of its use does not give the programmer any freedom.

JavaScript programming language

JavaScript logic is such that it is possible to distinguish a variable from an array only in the context of description or use, and this is a ghostly freedom. But the possibility of transforming anything into anything gives the programmer the necessary tools to build free data structures and algorithms for their processing.

JavaScript logic is similar to the logic of other languages, but this is where its similarity with other languages ​​ends. What can be done in JS can be recreated in other languages ​​the more precisely, the closer they are to JavaScript in terms of functionality and development.

JavaScript array syntax and semantics

JS arrays are objects. However, another object is a simple variable, but at the right time it can become a system of objects. A simple variable is also an array, if you give it the desired functionality.

It is generally accepted that two options for describing an array or object are considered sufficient: “[]” and “{}”. Square brackets are a simple array or object without methods. Curly braces are an associative array or object with methods. But these are only general points. The syntax of the above is much simpler:

js arrays

Applying this syntax can be significantly more complicated. The first two examples are ordinary arrays: they are created in a loop, contain letters of the Latin alphabet, differ only in letter case and indexes. In the first case, the index is the alphabetical number of the letter, in the second case, the index is the letter code.

The third example creates an associative array. Here the letter is an index, and its code is a value. If you wish, you can mix everything up.

The second example immediately demonstrates the JavaScript feature. The letter code is "A" = 65. On this simple basis, 64 undefined values ​​are automatically placed in the array.

Array Functionality

JS arrays do not have many methods, but the functionality of sort, forEach, filter, map, every / some, reduce / reduceRight deserves special attention. Here you can use your own functions to determine the desired action on array elements.

Character strings are a convenient form for representing arrays. An array can always be converted to a string and returned back. JS array is accessed into a string by the method:

  • sStr = aData.join ('"separator"')

All elements of the aData array become one line. When merging, you can use the “delimiter”, which can be empty '', a single character ',' or a string of characters.

When merging the elements of an array by one “separator”, nothing interferes in the string method:

  • aData = sStr.split ('"separator"')

Use a different “delimiter”. This mechanism allows you to build quite interesting information processing algorithms, although the main purpose of the transformation "JS arrays - strings" lies in the transmission and storage of data. A string is more compact than an array, more convenient for storage in a database, etc.

Arrays can be supplemented with other arrays (concat method), reverse the order of elements, sort, etc., but the most interesting and practical functionality lies in the first and last elements.

Stack data organization

He came last, left first - the idea of ​​a stack. JS arrays have succeeded in providing the functionality of this idea. If you put a new element in an array:

  • aData.push (oNew)

He will be at the end. If you extract the last element of the array (the pop method), it will be deleted from it. The next item retrieval operation will revert to the last item.

Stack data organization

In fact, adding elements to an array (push) increases it, while extracting elements (pop) reduces it. It is important that both methods work at the end of the array.

A similar shift / unshift pair works with the first element of the array, moving the remaining elements forward or backward. By the logic of things, it is more convenient and understandable to work with the last element of the array, but in some tasks it is important to work with prefixes, and not with suffixes.

If you combine the merging of elements into a string and the stack mechanism, you can further expand the functionality of JavaScript syntax. For example, each element of the fruit array (apple, pear, orange, mandarin, ...):

  • Then push / pop on the array element - work with the properties of a particular fruit: color, appearance, delivery date ...
  • Drain all the fruits into a single whole - the line and push / pop - these are the properties of the current availability of fruits: total weight, composition, quantity ...

Subarrays can be extracted from the array (slice method) and the original array will remain unharmed. However, if you remove the element of the array in js, it will be changed directly in place. The result of the method of removing the element (s) splice no.

Fruit array

Important. When deleting: the first parameter is the index of the first element to be deleted, the second parameter is the number of elements to be deleted. When extracting a subarray: the first parameter is the index of the first element, the second parameter is the index of the last. When retrieving, new JS arrays get the number of elements that is between the first and second parameter, inclusive.

Multidimensional JavaScript Arrays

JavaScript does not limit the programmer in the number of dimensions of the array. Nothing prevents creating designs (store, warehouse / shelf number, name of product / product group are taken as indexes):

  • aShop ['NoShop'] ['BoxF'] ['Fruits'] ['Fruit']; // fruit
  • aShop ['NoShop'] ['BoxB'] ['Berries'] ['Berry']; // berries
  • aShop ['NoShop'] ['BoxP'] ['Potatoes'] ['Potato']; // potato

That works. However, if in the first two constructions there are several variants of the types of fruits (berries), then there is no place for varieties of varieties and one more dimension is needed. In the third case, it is possible to indicate the varieties of potatoes, but it simply does not have species.

Obviously, in practice, such a solution is cumbersome, laborious in modification and testing. Not practical. It is best when the dimension is one, a maximum of two - in very rare cases.

A dynamic and practical solution in JS: an array of objects. Here you can immediately select an object as a store, in which there will be shelf objects (warehouses), and on the shelves there will be objects by type, variety, group ...

With this approach, dynamics immediately appears for each level of objects. You can bulk add or remove an array; JS offers methods for concatenating / retrieving and removing in place. In the first case, a group of goods, for example, moves from a warehouse to a store or vice versa, and in the second case, it is simply sold and disappears from the store (removed from the array).

Associations and associative arrays

In recent years, programming has been striving for simplicity. The struggle of programming languages ​​for survival did not show who won, but that simplicity is the key to true success. All languages ​​allow you to create space constructions in terms of dimensions, but in practice, modern programmers use two options:

  • simple (index) array;
  • associative array.

Both constructs have indices from zero to the current number of elements. The second also allows you to access the value for some name. According to the general logic of the language, in JS, an associative array is an ordered collection of pairs. And if necessary, a pair of "key" - "value" can be interchanged.

If there is an array of 16 pairs: digits of the hexadecimal number system, then creating a simple array of sixteen digits: from 0 to 15, you can select characters (not digits) as element values: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F '] and convert the number from decimal to hexadecimal and vice versa.

Associations are an internal property of data. A programmer can use associations to organize data structures at the object level. In this context, the main emphasis is on the creation of real objects, inside of which associative arrays by data properties are located.

Arrays of objects

The object in which the arrays of properties are located offers to use them within the meaning of their methods. Entities (types, varieties, properties) of apples and pears are different, they are even more different from citrus fruits or berries. Each fruit or berry (in appearance and variety, for example) is unique. A common object can be described as an abstraction of properties, but the methods here will be common to all types and varieties.

When goods arrive at the store, the array of objects received is filled. This array has its own functions of accessing the information contained in it and duplicates the methods of the objects included in it.

Array Application: Fruit Shop

In such a decision, for example, it is possible to calculate the quantity of goods, both for a specific position, and for all positions at once. You can display any available product, regardless of its type and grade. The method of exactly the product to which the appeal occurred will work.

In practice, such an object-oriented approach allows you not to contact the programmer during the operation of the system of objects, since it does not require reprogramming. The programmer provided for the properties, types, grades and methods of working with the goods. This is enough to sell everything that was discussed above and much more: peaches, cucumbers, eggplant, raisins, nuts ...

The system of objects in dynamics

Understanding the nature of the information to be processed is extremely important. The more complete the idea of ​​the subject area and the real objects that it manipulates, the more accurately you can describe the data and develop algorithms for their processing.

An ideal picture of a qualitatively solved problem: a list of elementary objects and systems of objects is compiled. All properties of each object and all connections between them are established.

The perfect solution

Each method of each object is functionally complete, and solves only one problem. An object can be accessed only through its methods, and therefore, it is not possible to disrupt its functioning from the outside.

The general solution is JavaScript functionality bound through the properties of DOM elements to functions that access objects only through their properties. If you need to develop something, either the communication interface with the created system of objects, or any object as necessary, is being finalized.

Source: https://habr.com/ru/post/K16664/


All Articles