Capitalize first letter of every other array element - javascript

I have an array of elements, ["apple", "cherry", "raspberry", "banana", "pomegranate"], and I want it so that every odd element is capitalized: ["Apple", "cherry", "Raspberry", "banana", "Pomegranate"].
I can capitalize every element in the array, and I can filter out every odd element, but not at the same time (i.e. filtering only shows the odd elements).
Does anyone have any approaches and/or recommendations for this? I've seen questions about capitalizing every other letter, retrieving every other array element, etc., but nothing like what I've asked (yet, I'm still looking).
function alts(arr) {
const newArr = arr.filter((el, idx) => {
if (idx % 2 === 0) {
return arr.map(a => a.charAt(0).toUpperCase() + a.substr(1));
}
})
return newArr;
}
console.log(alts(["apple", "cherry", "raspberry", "banana", "pomegranate"]));
// Just returns [ 'apple', 'raspberry', 'pomegranate' ]

Map instead of filtering - inside the callback, if even, return the capitalized portion, else return the original string:
function alts(arr) {
return arr.map((str, i) => i % 2 === 1 ? str : str[0].toUpperCase() + str.slice(1));
}
console.log(alts(["apple", "cherry", "raspberry", "banana", "pomegranate"]));

Try this:
function alts(arr) {
return arr.map((el, idx) => {
return idx % 2 == 0 ? el.charAt(0).toUpperCase() + el.substr(1) : el;
})
}
console.log(alts(["apple", "cherry", "raspberry", "banana", "pomegranate"]));
I map through the array and if the element's index is even (that's because index starts from 0, so it's flipped for us as we start counting from 1) then return the element with first letter capitalized, if it's an odd index, then just return the element itself.

function alts(arr) {
return arr.map((item, index) => {
if (index % 2 === 0) {
return item.charAt(0).toUpperCase() + item.substr(1);
} else {
return item
}
});
}
console.log(alts(["apple", "cherry", "raspberry", "banana", "pomegranate"]));
// Just returns [ 'apple', 'raspberry', 'pomegranate' ]

You can use a simple for-loop as follows:
function alts(arr=[]) {
const newArr = [...arr];
for(let i = 0; i < newArr.length; i+=2) {
const current = newArr[i];
if(current)
newArr[i] = current.charAt(0).toUpperCase() + current.substr(1);
}
return newArr;
}
console.log(alts(["apple", "cherry", "raspberry", "banana", "pomegranate"]));

Related

Use indexOf() to find every match in Javascript

If I have an array like const fruits = ["apple", "orange", "banana", "apple", "grape", "apple"] how can I use indexOf() (or another function if one exists) to find the index of every match?
Put another way, fruits.indexOf("apple") will only return 0 right now, but I want way to return an array with every matching index: [0, 3, 5].
Answer from mdn , Read the Docs
const indices = [];
const array = ["a", "b", "a", "c", "a", "d"];
const element = "a";
let idx = array.indexOf(element);
while (idx !== -1) {
indices.push(idx);
idx = array.indexOf(element, idx + 1);
}
console.log(indices);
// [0, 2, 4]
Here, inside the while loop, the second argument of indexOf method will determine the starting pointing point for finding index.
And the loop is updating it for next occurrences and storing it in an indices array
You can use .reduce():
const apples = fruits.reduce((result, fruit, index) => {
if (fruit === "apple")
result.push(index);
return result;
}, []);
You could of course wrap that in a function so that you could pass an array and a value to look for, and return the result.
You could use a combination of Array#map and Array#filter methods as follows:
const
fruits = ["apple", "orange", "banana", "apple", "grape", "apple"],
matchFruit = fruit => fruits
.map((f,i) => f === fruit ? i : -1)
.filter(i => i > -1);
console.log( matchFruit( "apple" ) );

How to move multiple elements to the beggining of the array?

I have a function that takes an array and string as arguments. The task is to chceck if the string occurs within the function and if does move to the first place of the array.
function moveToFirstPlace(['pizza', 'Pasta', 'Burger', 'PiZZa', 'pizzA'],'pizza')
in this example all pizzas have to be moved to the beggining of the array regardless of upper or lower letters.
You could sort the array and check the value and move this values to top.
function moveToFirstPlace(array, value) {
return array.sort((a, b) => (b.toLowerCase() === value) - (a.toLowerCase() === value));
}
console.log(moveToFirstPlace(['pizza', 'Pasta', 'Burger', 'PiZZa', 'pizzA'],'pizza'));
You can use push and unshift along with toLowerCase() to build a new array.
function moveToFirstPlace(items, key) {
let result = []
items.forEach(itm => {
itm.toLowerCase() == key.toLowerCase() ? result.unshift(itm) : result.push(itm)
})
return result
}
console.log(moveToFirstPlace(['pizza', 'Pasta', 'Burger', 'PiZZa', 'pizzA'], 'pizza'))
One way to do this is to apply filter to your array, once to identify the matches, and once for the non-matches. Then just concatenate both results:
function moveToFirstPlace(arr, str) {
str = str.toLowerCase();
const matches = arr.filter(elem => elem.toLowerCase() === str);
const misses = arr.filter(elem => elem.toLowerCase() !== str);
return matches.concat(misses);
}
var arr = moveToFirstPlace(['pizza', 'Pasta', 'Burger', 'PiZZa', 'pizzA'],'pizza');
console.log(arr);
This will maintain the original order of matching elements. Note that it does not mutate the original array, but returns a new array as result.
You could also use a more functional approach with reduce:
function moveToFirstPlace(arr, str) {
str = str.toLowerCase();
return arr.reduce((acc, elem) => (acc[+(elem.toLowerCase() === str)].push(elem), acc), [[], []])
.reduce((a, b) => a.concat(b));
}
var arr = moveToFirstPlace(['pizza', 'Pasta', 'Burger', 'PiZZa', 'pizzA'],'pizza');
console.log(arr);
Both solutions have a linear time complexity.
If efficiency is important, you can do this in-place with one O(n) pass (not counting toLowerCase) by running indexes from each end of the array and swapping when the right index finds pizza and the left finds non-pizza:
function moveToFirstPlace(arr, key){
let i = 0, j = arr.length -1
while (i < j){
while(!arr[j].toLowerCase().includes(key)) j--;
while(arr[i].toLowerCase().includes(key)) i++;
if (i < j)
[arr[j], arr[i]] = [arr[i], arr[j]];
i++;
j--;
}
}
let arr = ['pizza', 'Pasta', 'Burger', 'PiZZa', 'pizzA']
moveToFirstPlace(arr,'pizza')
console.log(arr)

Count occurring pairs in array - Javascript

I want to find and count the pair of values within an array.
For example:
var Array = ["Apple", "Pear", "Mango", "Strawberry", "Apple", "Pear", "Orange"];
Now I want to count how many times each pair (Apple and Pear, Pear and Mango and so on...) occurs in the array. If the array has uneven pair, the last value should then be zero.
The output of the array in the example should then be:
[2,1,1,1,1]
Notice that the "Apple, Pear" occurs 2 times so then the count will be two and put in the first number of the new array.
I hope I explained good enough
You could use a hash table for counting pairs by using two adjacent values and build a key of it for counting. Then use the values as result.
var array = ['Apple', 'Pear', 'Mango', 'Strawberry', 'Apple', 'Pear', 'Orange'],
count = {},
result;
array.reduce((a, b) => {
var key = [a, b].join('|');
count[key] = (count[key] || 0) + 1;
return b;
});
result = Object.values(count);
console.log(result);
console.log(count);
You could use sort() taking advantage of the fact that it passes the pairs needed to the callback:
var arr = ["Apple", "Pear", "Mango", "Strawberry", "Apple", "Pear", "Orange"];
var pairs = {}
arr.sort((a,b)=>{
(a+b in pairs)?pairs[a+b]++:pairs[a+b] = 1;
})
console.log(Object.values(pairs))
This is the simplest way to do it. It is similar to the answer given by #Nina Scholz above, but without having to join or anything like that. Also note that, while it defaults to pairs (i.e., 2), it is generic enough to check for triples, quadruples, and so on:
function CountMultiples(inputArray, quantity = 2) {
var count = {};
return inputArray.reduce((acc, val) => {
count[val] = (count[val] || 0) + 1;
return count[val] % quantity > 0 ? acc : ++acc;
}, 0);
};
var a = [1, 1, 2, 3, 4, 5, 6, 7, 8, 9, 9, 0, 0, 0, 6];
console.log(CountMultiples(a,4));//0
console.log(CountMultiples(a,3));//1
console.log(CountMultiples(a));//4

Javascript Remove specific only needed n-th elements of array

For example i have an array
var fruits = ["Banana", "Orange", "Apple", "Mango", "App", "Man"];
The code
fruits.splice(2, 2);
Return me output
Banana,Orange,App,Man
But how to return only 1,3,4 elements from array without looping?
So i will get
Orange,Mango,App
I imaging must be something like that
fruits.splice( fruits.indexOf(Orange,Mango,App), 1 );
You can use filter to filter out certain items:
fruits = fruits.filter(function (e, i) {
return i === 1 || i === 3 || i === 4;
});
Or if you want to keep certain items based on their identity (which seems to be what you're trying to do at the end of your question):
fruits = fruits.filter(function (e) {
return e === "Orange" || e === "Mango" || e === "App";
});
The same as JLRishe's answer but with the addition that you can pass in a list of those elements that you want to keep:
var fruits = ["Banana", "Orange", "Apple", "Mango", "App", "Man"];
var list = 'Orange, Mango, App';
alert(strip(fruits, list)); // ["Orange", "Mango", "App"]
function strip(arr, list) {
list = list.split(', ');
return arr.filter(function (el) {
return list.indexOf(el) > -1;
});
}
You may combine slice and splice methods:
var fruits = ["Banana", "Orange", "Apple", "Mango", "App", "Man"];
fruits.splice(2,1);
var x = fruits.slice(1,4);
x;
Explanation:
splice deletes 1 element starting at index 2 ( ie. "Apple" ).
slice extracts 3 elements starting at index 1 ( ie. "Orange", "Apple", "Mango", "App"; remember that at this time, the array no longer contains "Apple").
Variation (non-destructive):
var fruits = ["Banana", "Orange", "Apple", "Mango", "App", "Man"];
var x = fruits.slice(1,2).concat(fruits.slice(3,5));
x;

Is element in array js

Following an old question, I still have a problem:
a = ["apple", "banana", "orange", "apple"];
a.indexOf("apple") = 0
What is the easiest way to find BOTH indexes of "apple" element in array? I want to delete them both at once - is it possible?
That's the task for filter method:
var noApples = a.filter(function(el) { return el != "apple"; })
What is the easiest way to find BOTH indexes of "apple" element in array?
You asked that, but also asked about deleting. I'll tackle indexes first, then deletion.
Indexes:
There's no shortcut, you have to loop through it. You can use a simple for loop:
var indexes = [];
var index;
for (index = 0; index < a.length; ++index) {
if (a[n] === "apple") {
indexes.push(index);
}
});
Or two ES5 options: forEach:
var indexes = [];
a.forEach(function(entry, index) {
if (entry === "apple") {
indexes.push(index);
}
});
Or reduce:
var indexes = a.reduce(function(acc, entry, index) {
if (entry === "apple") {
acc.push(index);
}
return acc;
}, []);
...although frankly that does't really buy you anything over forEach.
Deletion:
From the end of your question:
I want to delete them both at once - is it possible?
Sort of. In ES5, there's a filter function you can use, but it creates a new array.
var newa = a.filter(function(entry) {
return entry !== "apple";
});
That basically does this (in general terms):
var newa = [];
var index;
for (index = 0; index < a.length; ++index) {
if (a[n] !== "apple") {
newa.push(index);
}
});
Array.indexOf takes a second, optional argument: the index to start from. You can use this inside a loop to specify to start from the last one.
var indices = [],
index = 0;
while (true) {
index = a.indexOf("apple", index);
if (index < 0) {
break;
}
indices.push(index);
}
Once indexOf returns -1, which signals "no element found", the loop will break.
The indices array will then hold the correct indices.
There is an example on the Mozilla page on indexOf which has some equivalent code. I'm not so much of a fan because of the increased duplication, but it is shorter, which is nice.
A for loop will do the trick. Or use forEach as T.J. Crowder suggests in his elegant answer.
I combined both an example of how to get appleIndexes and also how to "delete" them from the original array by virtue of creating a new array with all but apples in it. This is using oldSchool JavaScript :)
a = ["apple", "banana", "orange", "apple"];
appleIndexes = [];
arrayOfNotApples = [];
for (var i = 0; i < a.length; i++)
{
if (a[i] == "apple")
{
appleIndexes.push(i);
} else {
arrayOfNotApples.push(a[i]);
}
}
If you need to remove elements from an array instance without generating a new array, Array.prototype.splice is a good choice:
var a,
i;
a = ["apple", "banana", "orange", "apple"];
for (i = a.indexOf('apple'); i > -1; i = a.indexOf('apple')) {
a.splice(i, 1);
}
If you can use a new array instance, then Array.prototype.filter is a better choice:
var a,
b;
a = ["apple", "banana", "orange", "apple"];
b = a.filter(function (item, index, array) {
return item !== 'apple';
});
Use the start parameter in array.indexOf(element, start), as described in http://www.w3schools.com/jsref/jsref_indexof_array.asp.
Example:
var a = [1, 3, 4, 1];
var searchElement = 1;
var foundIndices = [];
var startIndex = 0;
while ((index = a.indexOf(searchElement, startIndex)) != -1) {
foundIndices.push(index);
startIndex = index + 1;
}
console.log(foundIndices); // Outputs [0, 3];
A good old while loop :
var i = a.length;
while (i--) {
if (a[i] === 'apple') {
a.splice(i, 1);
}
}
Inside a function :
function removeAll(value, array) {
var i = array.length;
while (i--) {
if (array[i] === value) {
array.splice(i, 1);
}
}
return array;
}
Usage :
removeAll('apple', a);
A couple of recursive solutions.
Javascript
function indexesOf(array, searchElement, fromIndex) {
var result = [],
index = array.indexOf(searchElement, fromIndex >>> 0);
if (index === -1) {
return result;
}
return result.concat(index, indexesOf(array, searchElement, index + 1));
}
function removeFrom(array, searchElement, fromIndex) {
var index = array.indexOf(searchElement, fromIndex >>> 0);
if (index !== -1) {
array.splice(index, 1);
removeFrom(array, searchElement, index);
}
return array;
}
var a = [0, 1, 0, 2, 0, 3, 0, 4, 0, 5, 0, 6, 0, 7, 0, 8, 0, 9, 0, 10, 0];
console.log(indexesOf(a, 0));
console.log(removeFrom(a, 0));
Output
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
On jsFiddle
The fastest, most compatible, route would be to walk the array backwards in a for loop.
for (var a = array.length;a--;)
if (array[a] == 'apple') array.splice(a,1);
if you want to remove all occurrences, you could also use Array.splice recursively
function remove(list, item) {
if(list.indexOf(item)<0)
return list;
list.splice(list.indexOf(item),1);
return list;
}

Categories

Resources