Array Methods Flashcards
let arr = [“I”, “go”, “home”];
delete arr[1];
alert( arr[1] ); // returns?
undefined
That’s natural, because delete obj.key removes a value by the key. It’s all it does. Fine for objects. But for arrays we usually want the rest of elements to shift and occupy the freed place. We expect to have a shorter array now.
let arr = [“I”, “go”, “home”];
delete arr[1];
alert( arr.length ); // returns?
3
now arr = [“I”, , “home”];
let arr = [“I”, “study”, “JavaScript”];
arr.splice(1, 1);
alert( arr ); // returns?
[“I”, “JavaScript”]
let arr = [“I”, “study”, “JavaScript”, “right”, “now”];
arr.splice(0, 3, “Let’s”, “dance”);
alert( arr ) // returns?
[“Let’s”, “dance”, “right”, “now”]
let arr = [“I”, “study”, “JavaScript”, “right”, “now”];
let removed = arr.splice(0, 2);
alert( removed ); // returns?
“I”, “study” <– array of removed elements
let arr = [“I”, “study”, “JavaScript”];
arr.splice(2, 0, “complex”, “language”);
alert( arr ); // returns?
“I”, “study”, “complex”, “language”, “JavaScript”
The method ________creates a new array that includes values from other arrays and additional items.
arr.concat
The _______ method allows to run a function for every element of the array.
arr.forEach
_______– looks for item starting from index from, and returns the index where it was found, otherwise -1.
arr.indexOf(item, from)
________item, from) – looks for item starting from index from, returns true if found.
arr.includes()
let arr = [1, 0, false];
alert( arr.indexOf(0) ); //
alert( arr.indexOf(null) ); //
1
-1
The method _______ is the same as indexOf, but looks for from right to left.
arr.lastIndexOf
Imagine we have an array of objects. How do we find an object with the specific condition?
arr.find(fn)
let result = arr.find(function(item, index, array) {
// if true is returned, item is returned and iteration is stopped
// for falsy scenario returns undefined
});
et users = [
{id: 1, name: “John”},
{id: 2, name: “Pete”},
{id: 3, name: “Mary”}
];
let user = users.find( );
write code
alert(user.name); // John
item => item.id == 1
const arr = [NaN];
alert( arr.indexOf(NaN) ); //
alert( arr.includes(NaN) );//
-1
true (correct)
The_____method creates a new array populated with the results of calling a provided function on every element in the calling array.
map()
let lengths = [“Bilbo”, “Gandalf”, “Nazgul”].map(item => item.length);
alert(lengths); //
5,7,6