You get a bonus - 1 coin for daily activity. Now you have 1 coin

Arrays: methods

Lecture



  1. Object.keys(obj)
  2. split method
  3. join method
  4. Remove from array
  5. splice method
  6. slice method
  7. Sort, sort(fn) method
    1. Own sorting order
  8. reverse
  9. concat
  10. indexOf/lastIndexOf
  11. Total

In this chapter, we will look at the built-in JavaScript array methods.

Object.keys(obj)

JavaScript has a built-in Object.keys (obj) method, which returns the keys of an object as an array. It is supported everywhere except IE <9:

1 var user = {
2 name: "Петя" ,
3 age: 30
4 }
5
6 var keys = Object.keys(user);
7
8 alert(keys); // name, age

In older browsers, the analog will be the cycle:

var keys = [];
for ( var key in user) keys.push(key);

Importance: 3

Let strings be an array of strings.

Write the function unique(strings) , which returns an array containing only the unique elements arr .

For example:

1 function unique(arr) {
2 /* ваш код */
3 }
4
5 var strings = [ "кришна" , "кришна" , "харе" , "харе" ,
6 "харе" , "харе" , "кришна" , "кришна" , "8-()" ];
7
8 alert( unique(strings) ); // кришна, харе, 8-()

Decision
Brute force solution (slow)

Go through the array nested loop.

For each element, we will look for whether this was already. If it was, ignore:

01 function unique(arr) {
02 var obj = {};
03 var result = [];
04
05 nextInput:
06 for ( var i=0; i
07 var str = arr[i]; // для каждого элемента
08 for ( var j=0; j // ищем, был ли он уже?
09 if (result[j] == str) continue nextInput; // если да, то следующий
10 }
11 result.push(str);
12 }
13
14 return result;
15 }
16
17 var strings = [ "кришна" , "кришна" , "харе" , "харе" ,
18 "харе" , "харе" , "кришна" , "кришна" , "8-()" ];
19
20 alert( unique(strings) ); // кришна, харе, 8-()

Let's see how fast it will work.

Suppose there are 100 elements in an array. If they are all the same, then result will consist of one element and the nested loop will be executed immediately. In this case, everything is fine.

And if all, or almost all the elements are different?

In this case, for each element you will need to bypass the entire current array of results, then add to this array.

    1. For the first element, this will cost 0 operations to access the result elements (it is empty for now).
    2. For the second element, this will cost 1 operation to access the result elements.
    3. For the third element, this will cost 2 operations to access the result elements.
    4. ... For the nth element - it will cost n-1 operations to access the result elements.

Total 0 + 1 + 2 + ... + n-1 = (n-1)*n/2 = n 2 /2 - n/2 (as the sum of an arithmetic progression), that is, the number of operations grows approximately like a square from n .

This is a very fast growth. For 100 elements - 4950 operations, for 1000 - 499500 (according to the formula above).

Therefore, this solution is suitable only for small arrays. Instead of the nested for you can use arr.indexOf , the situation will not change, since indexOf also looking for a brute force.

Solution with an object (quick)

The best technique for choosing unique lines is to use an auxiliary object. After all, the name of a property in an object is, on the one hand, a string, and on the other, it is always unique. Repeated writing to a property with the same name will overwrite it.

For example, if "харе" got into the object once ( obj["харе"] = true ), then the second such assignment will not change anything.

The solution below creates an obj = {} object and writes all the strings to it as property names. And then it collects the properties from the object into an array through for..in . Duplicate will be gone.

01 function unique(arr) {
02 var obj = {};
03
04 for ( var i=0; i
05 var str = arr[i];
06 obj[str] = true ; // запомнить строку в виде свойства объекта
07 }
08
09 return Object.keys(obj); // или собрать ключи перебором для IE<9
10 }
11
12 var strings = [ "кришна" , "кришна" , "харе" , "харе" ,
13 "харе" , "харе" , "кришна" , "кришна" , "8-()" ];
14
15 alert( unique(strings) ); // кришна, харе, 8-()

So you can put all the values ​​as keys in the object, and then get it.

[Open task in new window]

split method

The situation of real life. We are writing a message sending service and the visitor enters the names of those to whom to send it: Маша, Петя, Марина, Василий... But it’s much more convenient for us to work with an array of names than with a single line.

Fortunately, there is a split(s) method that allows you to turn a string into an array, breaking it up by separator s . In the example below, the delimiter is a comma and a space.

1 var names = 'Маша, Петя, Марина, Василий' ;
2
3 var arr = names.split( ', ' );
4
5 for ( var i=0; i
6 alert( 'Вам сообщение ' + arr[i]);
7 }

Second argument split

The split method has an optional second argument — a limit on the number of elements in the array. If there are more than specified, the remainder of the array will be discarded:

1 alert( "a,b,c,d" .split( ',' , 2 ) ); // a,b
In practice, it is rarely used.

Spelling

Calling str.split('') will break the string into letters:

1 var str = "тест" ;
2
3 alert( str.split( '' ) ); // т,е,с,т

join method

Calling arr.join(str) does exactly the opposite split . It takes an array and sticks it together into a string, using str as the delimiter.

For example:

1 var arr = [ 'Маша' , 'Петя' , 'Марина' , 'Василий' ];
2
3 var str = arr.join( ';' );
4
5 alert(str); // Маша;Петя;Марина;Василий

new Array + join = Repeat string

Code to repeat the line 3 times:

1 alert( new Array(4).join( "ля" ) ); // ляляля

As you can see, new Array(4) makes an array without elements of length 4, which join joins into a string, inserting the string "ля" between its elements .

As a result, since the elements are empty, the string is repeated. Such a little trick.

Importance: 5

The object has a className property that contains a list of “classes” - words separated by a space:

var obj = {
className: 'open menu'
}

Create the function addClass(obj, cls) , which adds the class cls to the list, but only if it is not already there:

1 addClass(obj, 'new' ); // obj.className='open menu new'
2 addClass(obj, 'open' ); // без изменений (класс уже существует)
3 addClass(obj, 'me' ); // obj.className='open menu new me'
4
5 alert(obj.className); // "open menu new me"

PS Your function should not add extra spaces.

Decision

The solution is to turn obj.className into an array using split .
After that, you can check the presence of the class in it, and if not, add it.

01 function addClass(obj, cls) {
02 var classes = obj.className ? obj.className.split( classes = obj.className ? obj.className.split( ' ' ) : [];
03
04 for ( var i=0; i
05 if (classes[i] == cls) return ; // класс уже есть
06 }
07
08 classes.push(cls); // добавить
09
10 obj.className = classes.join( ' ' ); // и обновить свойство
11 }
12
13 var obj = { className: 'open menu' };
14
15 addClass(obj, 'new' );
16 addClass(obj, 'open' );
17 addClass(obj, 'me' );
18 alert(obj.className) // open menu new me

PS An “alternative” approach to checking class presence by calling obj.className.indexOf(cls) would be incorrect. In particular, it will find cls = "menu" in the obj.className = "open mymenu" class obj.className = "open mymenu" .

PPS Check if your solution obj.className += " " + cls assignment obj.className += " " + cls . Does it not add an extra space if obj.className = "" originally?

[Open task in new window]

Importance: 3

Write the function camelize(str) , which converts strings of the form "my-short-string" to "myShortString".

That is, hyphens are deleted, and all words after them receive a capital letter.

For example:

camelize( "background-color" ) == 'backgroundColor' ;
camelize( "list-style-image" ) == 'listStyleImage' ;

This feature is useful when working with CSS.

PS The string methods charAt , split and toUpperCase useful to you.

Decision
Idea

The problem can be solved in several ways. One of them is to break the string by the hyphen str.split('-') , then successively construct a new one.

Decision

We split the string into an array, and then convert its elements and merge it back:

01 function camelize(str) {
02 var arr = str.split( '-' );
03
04 for ( var i=1; i
05 // преобразовать: первый символ с большой буквы
06 arr[i] = arr[i].charAt(0).toUpperCase() + arr[i].slice(1);
07 }
08
09 return arr.join( '' );
10 }

created: 2014-10-07
updated: 2021-12-05
132500



Rating 9 of 10. count vote: 2
Are you satisfied?:



Comments


To leave a comment
If you have any suggestion, idea, thanks or comment, feel free to write. We really value feedback and are glad to hear your opinion.
To reply

Scripting client side JavaScript, jqvery, BackBone

Terms: Scripting client side JavaScript, jqvery, BackBone