let distances = [
{ from: 'New York', to: 'Atlanta', distance: 880},
{ from: 'Austin', to: 'Seattle', distance: 1200},
{ from: 'Kansas', to: 'Portland', distance: 1340}
]
Write a function that returns an array that is the same as the input array, except that the distance is converted to miles (*.621371)
function f1(array) {
let result = [];
for (let i=0; i<distances.length;++i) {
result.push(
{
...distances[i],
distance: distances[i]* 0.621371
})
}
return result;
}
function f2(array) {
return distances.map((x)=> { return { ...x, distance: x* 0.621371 }});
}
Write a function that returns the elements in the array that have a distance < 1000
function f1(array) {
let filterDistances = []
for (let i = 0; i < distances.length; i ++) {
if (distances[i].distance < 1000) {
filterDistances.push(distances[i])
}
}
return filteredDistances;
}
function f2(array) {
return distances.filter(item => item.distance < 1000);
}
Write a function that returns the total distance of all the elements in the array.
function f1(array) {
let total = 0
for (let i = 0; i < distances.length; i++) {
total += distances[i].distance;
}
return total;
}
function f2(array) {
return distances.reduce((acc, item) => acc+ item.distance, 0);
}
Write a function that returns the total distance (in miles) of all of the items that are < 1000 km
function f1(array) {
let total = 0
for(let i = 0; i < distances.length; i++){
if(distances[i].distance < 1000){
total += distances[i].distance * 0.621371;
}
}
return total;
}
function f2(array) {
return distances
.filter(item => item.distance < 1000)
.map(item => item.distance * 0.621371)
.reduce((prev, distance) => prev + distance, 0);
}
Write a function capitalize that takes a string and uses .map to return the same string in all caps.
// ex. capitalize('whoop') // => 'WHOOP'
function capitalize(input) {
return [...input].map(x => x.toUpperCase()).join("");
}
Now write a new function called swapCase that takes a string of words and uses .map and your newly written capitalize() function to return a string where every other word is in all caps.
function swapCase(input) {
return input
.split(" ")
.map((x, idx) => (idx % 2 ? x : capitalize(x)))
.join(" ");
}
Write a function that takes a string and returns an object representing the character count for each letter. Use .reduce to build this object.
const binarySearchIterative = (arr, target) => {
let left = 0;
let right = arr.length-1;
while (left<=right) {
let mid = left + Math.floor((right-left)/2);
if (arr[mid]===target) {
return target;
}
if (target>arr[mid]) {
left = mid+1;
}
else {
right = mid-1;
}
}
return -1;
}