Data structures Flashcards
What two main things replace internal tables in JS?
Arrays and Objects
How are items in an array separated?
By a comma
Give an example of defining an array
Let myArray = [“Bob”,”Tanya”,”Henry”]
What is the index of the first item in an array?
0
List 5 common array methods
.sort
.reverse
.some
.length
.push
.splice
Give the syntax for sorting an array of numbers by ascending and descending order
//sort a number array
Let myArray = [“C”,”D”,”A”,”B”]
myArray.sort(a, b) => a - b); //ascending
myArray.sort((a, b) => b - a);//descending
Give the syntax for sorting a non-numeric array
//sort
Let myArray = [“Ann”,”Karen”,”Bobby”];
myArray.sort();
myArray.reverse();
What are the two optional parameters for sorting that must be used when sorting numbers?
a = current value
b = next value
so
myArray.sort((a, b) => a - b);
means compare the current value to the next value and if a - b if b is less than a then b needs to move in front of a.
myArray.sort((a, b) => b - a): would be a descending sort. If b is less than a then a should move in front of b as this is descending
Explain what the array.some function does and give an example of it’s syntax
The .some searches for a value in the array
Let myArray = [“Bob”,”Henry”,”Karen”]
//check for value Karen
Let found = myArray.some((element) => element === “Karen”);
//Found will have a value of true
Give an example of the .length function
let myArray = [“bob”,”henry”,”tanya”];
let myLen = myArray.length();
//mylen will equal 3
give an example of the .push function
Let myArray = [“Pasha”,”Misha”];
myArray.push(“Isa”);
//isa will be added to end of the array
How is an array written to the console?
Let myArray = [“Isa”,”Bob”];
console.table(myArray);
What does the splice function do and what is the syntax?
myArray.splice(
“what index should the insert be
“0 to many lines should be removed
“what should be added
)
//so add “pasha” as the second item
Let myArray = [“Isa”,”Misha”];
myArray.splice(1, 0, “Pasha”];
How can an item be deleted from an array?
let myArray = [“Pasha”,”Isa”,”Misha”];
myArray.splice(1,1);
//the above would remove “Isa”
How can an item be replaced in an array?
let myArray = [“cat1”,”cat2”,”dog1”]
myArray.splice(0,2,”Dog0”);
//cat1 and cat 2 will be replaced by Dog0
//or
myArray = [“cat”,”dog”,”lizard”];
myArray.splice(1,1,”Isa”,”Pepe”)
//now cat, isa, pepe, lizard