Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
71 changes: 71 additions & 0 deletions array-methods/1-array.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,34 +6,94 @@ var strings = ["this", "is", "a", "collection", "of", "words"];

// Find largest number in numbers

var maxNum = Math.max(...numbers);
console.log(maxNum);

// Find longest string in strings

var lengthArray = [];
var num = 0;
var longestString = "";
strings.forEach(function(element) {
if (element.length > num) {
num = element.length;
longestString = element;
}
});

// Find all the even numbers

var evenArray = numbers.filter(element => element % 2 == 0);
console.log(evenArray); // [12, 4, 18, 6]

// Find all the odd numbers

var oddArray = numbers.filter(element => element % 2);
console.log(oddArray); // [1, 9, 7, 11, 3, 101, 5]

// Find all the words that contain 'is' use string method 'includes'

var containsIs = strings.filter(element => element.includes("is"));
console.log(containsIs);

// Find all the words that contain 'is' use string method 'indexOf'

var arr = [];
var containsIsss = strings.forEach(function(element) {
if (element.indexOf("is") != -1) {arr.push(element);}
});
arr; // ["this", is]

// Check if all the numbers in numbers array are divisible by three use array method (every)

var divisibleByThree = numbers.every(function(element) {element % 3 == 0});
divisibleByThree // false

// Sort Array from smallest to largest

var sortStr = strings.sort();
var numArray = numbers.sort(function (a, b) {return a-b;});

sortStr; // ["a", "collection", "is", "of", "swastik"]
numArray; // [1, 3, 4, 5, 6, 7, 9, 11, 12, 18, 101]

// Remove the last word in strings

strings.pop();
strings // ["this", "is", "a", "collection", "of"]

// Add a new word in the array

strings.push("newWord");
strings // ["this", "is", "a", "collection", "of", "newWord"]

// Remove the first word in the array

strings.shift();
strings // ["is", "a", "collection", "of", "newWord"]

// Place a new word at the start of the array use (upshift)

strings.unshift("Hello");
strings // ["Hello", "is", "a", "collection", "of", "newWord"]

// Make a subset of numbers array [18,9,7,11]

var subSet = numbers.slice(3, 7);
subSet; // [18, 9, 7, 11];

// Make a subset of strings array ['a','collection']

var subStr = strings.slice(3, 7);
subStr; // ["a", "collection"]

// Replace 12 & 18 with 1221 and 1881

numbers.splice(3, 1, 1881);
numbers.splice(1, 1, 1221);

numbers; // [1, 1221, 4, 1881, 9, 7, 11, 3, 101, 5, 6]

// Replace words with string in strings array

// Customers Array
Expand All @@ -45,6 +105,17 @@ var customers = [
];
// Find all customers whose firstname starts with 'J'

var startWithJ = customers.filter(element => element.firstname.startsWith('J'));
startWithJ;

// Create new array with firstname and lastname

var nameArray = [];
var name = customers.forEach(function(element) {
nameArray.push(`${element.firstname} + ${element.lastname}`);
});
nameArray; // ["Joe Blogs", "John Smith", "Dave Jones", "Jack White"]

// Sort the array created above alphabetically

nameArray.sort(); // ["Dave Jones", "Jack White", "Joe Blogs", "John Smith"]
35 changes: 31 additions & 4 deletions array-methods/2-array.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,16 @@ var words = [
//Write a function findLongestWord that takes an array of words and returns the longest one.
//If there are 2 with the same length, it should return the first occurrence.

var lengthArray = [];
var num = 0;
var longestString = "";
words.forEach(function(element) {
if (element.length > num) {
num = element.length;
longestString = element;
}
});
// This will return the first occurence of longest word.



Expand All @@ -18,14 +28,24 @@ var numbers1 = [6, 12, 1, 18, 13, 16, 2, 1, 8, 10];
// Use reduce method of array
// Use the above sum and calculate the average.

var reducer = (accumulator, currentValue) => accumulator + currentValue;
var sum1 = numbers1.reduce(reducer);


var avg1 = sum / numbers1.length;
avg1; // 8.7

var numbers2 = [2, 6, 9, 10, 7, 4, 1, 9];
//Write a function averageNumbers that receives an array of numbers2 and calculate the average of the numbers



var sum2 = 0;
function averageNumbers(numArray) {
numArray.forEach(function(element) {
sum2 += element;
});
return sum2 / numArray.length;
}
averageNumbers(numbers2); // 48 / 8 = 6.

var words2 = [
'seat',
Expand All @@ -41,5 +61,12 @@ var words2 = [
];
//Write a function averageWordLength that receives an array of words2 and calculate the average length of the words.



var word2len = 0;
function avgWords(words2) {
words2.forEach(function(element) {
word2len += element.length;
});
var wordAvg = word2len / words2.length;
return wordAvg;
}
avgWords(words2); // 5.3
54 changes: 54 additions & 0 deletions array-methods/3-array.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,11 @@ var words = [
// Write a function uniqueArray that receives an array of words as a parameter. And remove the duplicates, and return a new array.
// (indexOf)

function uniqueArray(words) {
var wordsFilter = words.filter((element, index) => words.indexOf(element) == index);
return wordsFilter;
}



var words2 = [
Expand All @@ -30,6 +35,11 @@ var words2 = [

// Write a function doesWordExist that will take in an array of words as one argument, and a word to search for as the other. Return true if it exists, otherwise, return false. Don't use indexOf for this one.

function doesWordExist(words2, searchItem) {
return words2.includes(searchItem);
}

doesWordExist(words2, 'machine'); // true;



Expand All @@ -50,7 +60,19 @@ var words3 = [

// Write a function howManyTimes that will take in an array of words as one argument, and a word to search for as the other. The function will return the number of times that word appears in the array.

function howManyTimes(words3, searchItem) {
var arr = [searchItem];
words3.forEach(element => {
if(arr.includes(element)) {
arr.push(element);
}
});
return arr.length - 1;
}

howManyTimes(words3, 'matter'); // 4
howManyTimes(words3, 'machine'); // 1
howManyTimes(words3, 'matter-machine'); // 0



Expand All @@ -74,6 +96,14 @@ let data = [
}
]

data.reduce((acc, value) => {
if (value.country == 'China') {
return acc;
} else {
return acc + value.pop;
}
}, 0);


// Use reduce method and summorize the collection like
// { banana: 2, cherry: 3, orange: 3, apple: 2, fig: 1 }
Expand All @@ -91,6 +121,30 @@ const fruitBasket = [
'fig'
];

// var finalObject = {};

// fruitBasket.reduce((acc, value) => {
// if (finalObject[acc] == 0) {
// finalObject[acc]++;
// }
// if (!finalObject[value]) {
// finalObject[value] = 0;
// }

// finalObject[value]++;
// }, 0);

// finalObject;

fruitBasket.reduce((acc, value) => {
if (acc[value]) {
acc[value]++;
} else {
acc[value] = 1;
}
return acc;
}, {});



// Bonus Question (Solve only if you have time)
Expand Down
25 changes: 25 additions & 0 deletions array-methods/4-array.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,11 +31,36 @@ var data = [

// your code goes here

var sum = 0;
function sumDogAge() {
for (var i = 0; i < data.length; i++) {
if (data[i].type == 'dog') {
sum += data[i].age * 7;
}
}
}

sumDogAge(); // 105

// Solution is 105


// Write the same function using
// 1. filter - for filtering the cat or dog
// 2. map - to multiply human year to dog year
// 3. reduce - to accumulate total age.

// Solution 105

function sumDogAge() {
var typeDog = data.filter(element => element.type == 'dog');
var dogYear = typeDog.map(element => element.age * 7);
var sum = dogYear.reduce((x, y) => x + y);

return sum;
}

sumDogAge();


// Solution 105
16 changes: 13 additions & 3 deletions array-methods/5-object.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
// 1. Write a JavaScript program to list the properties and values of a JavaScript object. (Object.keys)


function listKeyValues(obj) {
Object.entries(obj);
}

// 2. Write a JavaScript program to delete the rollno property from the following object. Also print the object before or after deleting the property.
var student = {
Expand All @@ -9,7 +11,15 @@ var student = {
rollno : 12
};

function deleteRollNo (obj) {
delete obj.rollno;
console.log(obj);
}
deleteRollNo(student);



// 3. Write a function to get the length of an object.
// 3. Write a function to get the length of an object.
function objLen(obj) {
return Object.keys(obj).length;
}
objLen(student);
Loading