This is a work-in-progress cheatsheet for JS arrays. Please feel free to leave a comment if this has helped you or you would like to suggest anything.
- Create an array
- Empty an array
- Clone an array
- Get last item
- Remove first item
- Remove last item
- Add new item(s) to beginning
- Add new item(s) to end
- Overwrite item at a specific index
- Add new item(s) at a specific index
- Remove single item at a specific index
- Remove several items
- Reverse an array
- Delimit an array
- Sort in numerical order
- Sort in alphabetical order
- Join two arrays together
- Copy specific item(s)
- Augment items within an array
- Return true if every item meets a condition
- Return true if at least one item matches a condition
- Execute a function once per array item
- Filter an array
- Detect an array
- ES5 and above
- ES4 and below
- Simple FIFO queue
- Find index of an item
- ES5 and above
- ES4 and below
- Randomise an array
- Chaining Methods
var meals = ['breakfast', 'lunch', 'dinner'] ;
Keeping references intact.
var meals = ['breakfast', 'lunch', 'dinner'];
meals.splice(0, meals.length);
or
var meals = ['breakfast', 'lunch', 'dinner'];
meals.length = 0
var meals = ['breakfast', 'lunch', 'dinner'];
var copy = meals.slice();
// ['breakfast', 'lunch', 'dinner']
var meals = ['breakfast', 'lunch', 'dinner'];
meals[meals.length - 1];
// 'dinner'
Or
var meals = ['breakfast', 'lunch', 'dinner'];
meals.slice(-1)[0];
// 'dinner'
var meals = ['breakfast', 'lunch', 'dinner'];
meals.shift();
// 'breakfast'
meals;
// ['lunch', 'dinner']
var meals = ['breakfast', 'lunch', 'dinner'];
meals.pop();
// 'dinner'
meals;
// ['breakfast', 'lunch'];
var meals = ['lunch', 'dinner'];
meals.unshift('breakfast');
// 3 - the array length
meals;
// ['breakfast', 'lunch', 'dinner']
var meals = ['breakfast', 'lunch', 'dinner'];
meals.push('supper');
// 2
meals;
// ['breakfast', 'lunch', 'dinner', 'supper'];
var meals = ['breakfast', 'lunch', 'dinner'];
meals[1] = 'brunch';
// ['breakfast', 'brunch', 'dinner'];
Or
var meals = ['breakfast', 'lunch', 'dinner'];
meals.splice(1, 1, 'brunch');
var meals = ['breakfast', 'lunch', 'dinner'];
meals.splice(1, 0, 'brunch', 'more brunch');
// ['breakfast', 'brunch', 'more brunch', 'lunch', 'dinner']
var meals = ['breakfast', 'lunch', 'dinner'];
meals.splice(1, 1);
// ['lunch']
meals;
// ['breakfast', 'dinner']
var meals = ['breakfast', 'lunch', 'dinner'];
meals.splice(1, 2);
// ['lunch', 'dinner']
meals;
// ['breakfast']
var meals = ['breakfast', 'lunch', 'dinner'];
meals.reverse();
// ['dinner', 'lunch', 'breakfast'];
var meals = ['breakfast', 'lunch', 'dinner'];
meals.join(' AND ');
// 'breakfast AND lunch AND dinner'
var meals = ['dinner', 'supper', 'breakfast', 'lunch'];
meals.sort();
// ['breakfast', 'dinner', 'lunch', 'supper']
var numbers = [1438,2605,794,3947,6241,11745,2585];
numbers.sort(function(a, b) {
return a - b;
});
// [794,1438,2585,2605,3947,6241,11745]
var dayTimeMeals = ['breakfast', 'lunch'];
var nightTimeMeals = ['merienda', 'dinner'];
var allTheMeals = dayTimeMeals.concat(nightTimeMeals);
// ['breakfast', 'lunch', 'merienda', 'dinner']
var meals = ['breakfast', 'lunch', 'dinner', 'supper'];
nightTimeMeals = meals.slice(2,4);
// ['dinner', 'supper']
var meals = ['breakfast', 'lunch', 'dinner'];
var type = ['king', 'prince', 'pauper'];
meals.map(function(item, i) {
return item + ' like a ' + type[i];
});
// ["breakfast like a king", "lunch like a prince", "dinner like a pauper"]
var meals = ['breakfast', 'lunch', 'dinner', 'supper'];
meals.every(function(item){ return item.length > 0 });
// true
meals.every(function(item){ return item.length > 6 });
// false
var meals = ['breakfast', 'lunch', 'dinner', 'supper'];
meals.some(function(item){ return item === 'lunch';});
// true
meals.some(function(item){ return item === 'burgers!!';});
//false
var meals = ['breakfast', 'lunch', 'dinner', 'supper'];
meals.forEach(function(currentValue, index, arr){
console.log(index, currentValue, arr);
});
var meals = ['breakfast', 'lunch', 'dinner', 'supper'];
meals.filter(function(item) {
return item !== 'breakfast';
});
// ['lunch', 'dinner', 'supper'];
var meals = ['breakfast', 'lunch', 'dinner'];
Array.isArray(meals)
// true
var meals = ['breakfast', 'lunch', 'dinner'];
function isArray(arr) {
return !!(Object.prototype.toString.call(arr) === '[object Array]');
}
isArray(meals);
// true
var meals = ['breakfast', 'elevenses', 'brunch'];
meals.shift();
meals.push('lunch');
// ['elevenses', 'brunch', 'lunch']
meals.shift()
meals.push('afternoon tea');
// ['brunch', 'lunch', 'afternoon tea']
// ... and so on ...
var meals = ['breakfast', 'elevenses', 'brunch'];
meals.indexOf('brunch');
// 2
var meals = ['breakfast', 'elevenses', 'brunch'];
function inArray(arr, item){
var found = -1,
i = arr.length;
while(--i >= 0) {
if(arr[i] === item){
found = i;
break;
}
}
return found;
}
inArray(meals, 'brunch');
// 2 - the index of the item in the array
inArray(meals, 'dinner');
// -1
function randomiseArray(arr) {
var buffer = [], start;
for(var i = arr.length; i >= arr.length && i > 0;i--) {
start = Math.floor(Math.random() * arr.length);
buffer.push(arr.splice(start, 1)[0])
};
return buffer;
}
randomiseArray([0,1,2,3,4]);
// [2,1,0,3,4]
randomiseArray([0,1,2,3,4]);
// [3,2,1,4,0]
randomiseArray([0,1,2,3,4]);
// [1,2,4,0,3]
var meals = [
{type: 'breakfast', name: 'Full English', calories: 1500},
{type: 'breakfast', name: 'Colacao', calories: 260},
{type: 'breakfast', name: 'Croissant and jam', calories: 520},
{type: 'breakfast', name: 'Granola with Greek yoghurt and blueberries', calories: 680},
{type: 'brinner', name: 'Shepherds Pie with strawberry yoghurt', calories: 915},
{type: 'brinner', name: 'Milky Porridge with beef and green beans', calories: 875},
{type: 'dinner', name: 'Phad Thai', calories: 750},
{type: 'dinner', name: 'Chicken Katsu curry and rice', calories: 830},
];
function getMealsByMaxCalories(meals, maxCalories, dailyAllowance) {
return meals
.filter(function(meal) {
return meal.calories <= maxCalories;
})
.map(function(meal) {
return {
name: meal.name,
calories: meal.calories,
percentageOfDailyAllowance: meal.calories / dailyAllowance * 100
}
});
}
getMealsByMaxCalories(meals, 850, 2000);
/*
[
{
"name": "Colacao",
"calories": 260,
"percentageOfDailyAllowance": 13
},
{
"name": "Croissant and jam",
"calories": 520,
"percentageOfDailyAllowance": 26
},
{
"name": "Granola with Greek yoghurt and blueberries",
"calories": 680,
"percentageOfDailyAllowance": 34
},
{
"name": "Phad Thai",
"calories": 750,
"percentageOfDailyAllowance": 37.5
}
]
*/
There are multiple errors in your inArray function!
Here's how it should be:
First, --i will NOT find the index if the item is the first in the array when --i yields 0 it evaluates to false and thus the first item in the array is not found. Second, you declare i AND len, no need to declare len as well. Third: you do not break after the item has been found which is very inefficient in large arrays as it will continue to loop through the entire array though the item has already been found. Fourth: you used query to compare to, but it should be item.