I have an array like this
const arr = ["Apple", "Banana", "Cherry", "Orange", "Avocado", "Ananas", "Pineapple];
I need a function that returns an array with all the Elements from arr, that match the given character sequence. The order of the characters is of importance.
Given "ppl" the function should return ["Apple", "Pineapple"].
Given "n" the function should return ["Banana", "Orange", "Ananas", "Pineapple"].
Given "voca" the function shoould return ["Avocado"]
Given "rr" the function should return ["Cherry"], while given a "r" the function should return ["Cherry", "Orange"].
try this
const arr = ["Apple", "Banana", "Cherry", "Orange", "Avocado", "Ananas", "Pineapple"];
const search = query => arr.filter(s => s.toLowerCase().includes(query))
console.log(search("n"))
console.log(search("ppl"))
It is also possible like this
const arr = ["Apple", "Banana", "Cherry", "Orange", "Avocado", "Ananas", "Pineapple"];
const query = 'pp';
arr.filter(element => element.includes(query));
It's pretty straight forward using filter function and indexOf
const arr = ["Apple", "Banana", "Cherry", "Orange", "Avocado", "Ananas", "Pineapple"];
const cond = 'ppl'
console.log(arr.filter(x => x.indexOf(cond) > -1 ))
<script>
function checkPattern(str, pattern) {
var len = pattern.length;
if (str.length < len) {
return false;
}
for (var i = 0; i < len - 1; i++) {
var x = pattern[i];
var y = pattern[i + 1];
var last = str.lastIndexOf(x);
var first = str.indexOf(y);
if (last === -1 || first === -1 || last > first) {
return false;
}
}
return true;
}
var str = "engineers rock";
var pattern = "gin";
document.write(checkPattern(str, pattern));
</script>
You can use Array.prototype.filter() combined with String.prototype.includes():
const result = arr.filter(el => el.toLowerCase().includes(input))
Code:
const arr = ["Apple", "Banana", "Cherry", "Orange", "Avocado", "Ananas", "Pineapple"]
const inputs = ["ppl", "n", "voca", "rr", "r"]
inputs.forEach(input => {
const result = arr.filter(el => el.toLowerCase().includes(input))
console.log(`Result for ${input}:`, result)
})
Related
I'm having trouble wrapping my head around this, but let's say there an array with these elements:
["apple", "banana", "pear", "kiwi", "orange"]
I would like to transfer this array into:
["apple", "apple/banana", "apple/banana/pear", "apple/banana/pear/kiwi", "apple/banana/pear/kiwi/orange"]
I need this in JavaScript and I'm not sure how to achieve it.
Please note that I'm currently working with ES5.
Here's a simple implementation of what you're trying to do :
ES5
var input = ["apple", "banana", "pear", "kiwi", "orange"];
var prev = '';
var output = input.map(function (el) {
el = prev + el; prev = el + '/'; return el;
});
console.log(output);
ES6
let input = ["apple", "banana", "pear", "kiwi", "orange"];
let prev= '';
let output = input.map( el => { el = prev + el; prev = el+'/'; return el})
console.log(output)
Array.map() is meant for these problems.
The map() method creates a new array with the results of calling a provided function on every element in the calling array.
And while walking through the array with map you can use join() and slice() to concatenate certain values from an original array.
let input = ["apple", "banana", "pear", "kiwi", "orange"];
let output = input.map((el, index) => {
return (input[index-1]) ? input.slice(0, index+1).join('/') : el;
})
output:
Array [
"apple",
"apple/banana",
"apple/banana/pear",
"apple/banana/pear/kiwi",
"apple/banana/pear/kiwi/orange"
]
Some more explanation on what is happening in those 3 lines:
// let's write it out.
let output = input.map((el, index) => {
// If there is a previous index of this array, we need to join it with this one
if (input[index-1]) {
// all previous values including this one
let a = input.slice(0, index+1)
// concatenate them all with a seperator
let b = a.join('/');
return b;
} else {
// if not just return the element
return el;
}
})
You wrote: Please note that I'm currently working with ES5.
Unfortunately, some people do not understand anymore what is ES5 and suggest ES6 solutions (with arrow function expressions, let statements and constants).
Array.map was added to the ECMA-262 standard in the ECMAScript 5.1 edition. It is fully supported by all modern browsers inclusive IE9.
var input = ["apple", "banana", "pear", "kiwi", "orange"],
output = input.map(function(elem, index)
{
return index > 0 ? input.slice(0, index + 1).join('/') : elem;
});
console.log(JSON.stringify(output, null, '\t'));
var fruits = ["apple", "pear", "orange", "banana"];
var i;
for( i=0; i<fruits.length; i++) {
if (i == 0){
continue;
}
var temp = fruits[i];
fruits[i] = fruits[i-1] + "/" + temp;
}
for( i=0; i<fruits.length; i++) {
print(fruits[i]);
}
Here you go!
Points to remember:
Concatenation Operator
For loop
continue statement
Arrays
var array = ["apple", "banana", "pear", "kiwi", "orange"]
var all = [];
var str ="";
for(var i=0;i< array.length;i++)
{
if(array[i-1]){
str += array[i-1]+'/';
all.push(str+array[i])
}
else all.push(array[i])
}
console.log(all);
Time to .reduce it
This works by creating a new array, and accessing the last placed string and appending a '/' and then the next string current.
yourArray.reduce((newArray, current) => newArray.concat(newArray.length > 0 ? newArray[newArray.length - 1] + '/' + current : current), [])
// long version:
yourArray.reduce((newArray, current) => {
if (newArray.length > 0) {
return newArray.concat(current)
} else {
const previousString = newArray[newArray.length - 1]
return newArray.concat(previousString + '/' + current)
}
}, [])
For the ones that do use ES6 or can transpile the code to ES5 (Using i.e: Babel)
const a = ["a", "b", "c", "d", "e"];
const res = a.map((_, i) => a.slice(0, i+1).join("/"));
console.log(res);
This question already has answers here:
How to sort strings in JavaScript
(16 answers)
Closed 3 years ago.
I have a list of names (i.e strings) from user input, and I would like to sort them in alphabetic order
my little project
You can use something like this:
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort()
Also you can write your own method:
sort(function (a, b) {
if (a > b) {
return -1;
}
if (b > a) {
return 1;
}
return 0;
});
var names = ["Banana", "Orange", "Apple", "Mango"];
names.sort();
or
var names = ["Banana", "Orange", "Apple", "Mango"];
names.sort(function(a, b){return a-b})
const player = document.getElementById('txt')
const button = document.getElementById('btn')
const team = document.getElementById('team')
const player_array = [];
function newPlayer () {
player_array.push(player.value);
shuffle_list();
//paragraph.textContent.sort
player.value = ''
player.focus()
}
function shuffle_list () {
player_array.sort();
team.innerHTML = '';
for (let p of player_array) {
const paragraph = document.createElement('p')
team.appendChild(paragraph)
paragraph.textContent = p;
}
}
button.addEventListener('click', newPlayer)
Fixed it for you
is that possible to create a multidimensional array, then push another array on each those multidimensional array ??
lets say the variable
arr = ["apple", "orange", "Avocados", "Tomato", "Tangerine"]
and the output I want is:
[
["a", ["apple", "avocados"] ],
[ "o", ["orange"] ],
["T", ["Tomato", "Tangering"]]
]
the example about to create first initial to new arr multidimensional before the output, we create like this, [[ "a"],["o"],["T"]] and output i want is on above ( the box code )
then check again if that first initial same with a first initial array, push it on those 2d arrays, that is for example, but if array length for others is not same, we should create a function, to use it again late
You could group the data by finding the array with the value or create a new array for the result set.
var array = ["apple", "orange", "avocados", "tomato", "tangerine"],
result = array.reduce((r, s) => {
var temp = r.find(([c]) => c === s[0]);
if (temp) {
temp[1].push(s);
} else {
r.push([s[0], [s]]);
}
return r;
}, []);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
A better structure would be to use a Map and collect all strings to the same starting letter.
var array = ["apple", "orange", "avocados", "tomato", "tangerine"],
result = Array.from(
array.reduce((map, s) => map.set(s[0], [...(map.get(s[0]) || []), s]), new Map)
);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
I think your output is too complicated to produce. You can simplify the output format like this:
{
"a" : ["apple", "avocados"],
"o": ["orange"],
"t": ["Tomato", "Tangering"]
}
You can produce output like this with ease with Lodash:
_.groupBy(["apple", "orange", "Avocados", "Tomato", "Tangerine"], function (item) {
return item[0].toLowerCase()
});
Or with iterate the array:
var arr = ["apple", "orange", "Avocados", "Tomato", "Tangerine"];
var output = [];
for (var i = 0 ; i < arr.length ; i++){
if (output[arr[i][0].toLowerCase()] == undefined)
output[arr[i][0].toLowerCase()] = [];
output[arr[i][0].toLowerCase()].push(arr[i]);
}
You can reduce the array to object
var arr = ["apple", "orange", "Avocados", "Tomato", "Tangerine"];
var output = arr.reduce(function(res, item) {
if(Object.keys(res).indexOf(item.charAt(0).toLowerCase()) == -1)
{
res[item.charAt(0).toLowerCase()] = [];
}
res[item.charAt(0).toLowerCase()].push(item);
return res;
},{});
console.log(output);
Yet another alternative using vanilla JavaScript and some functional programming:
const input = ["apple", "orange", "Avocados", "Tomato", "Tangerine"]
// (1) An unique list of lower-cased initials of all given input words
// * Set gives us the unique behavior
const initials = [...new Set (
input.map (([initial]) => initial.toLowerCase ())
)]
const byInitial = ([initial]) => ([initial_]) =>
initial_.toLowerCase () == initial
// (2) This groups each world by their initial
// Iterates each lowered initial and filters the input by each initial
// to build the groups!
const grouped = initials.reduce ((o, initial) =>
[
...o, // <--- this accumulates the new result with the previous one
[
initial,
input.filter (byInitial(initial))
]
], [])
console.log (grouped)
Yet another approach, now using zip:
const input = ["apple", "orange", "Avocados", "Tomato", "Tangerine"]
// (1) An unique list of lower-cased initials of all given input words
// * Set gives us the unique behavior
const initials = [...new Set (
input.map (([initial]) => initial.toLowerCase ())
)]
const byInitial = ([initial]) => ([initial_]) =>
initial_.toLowerCase () == initial
// (2) This builds groups each world by their initial
const groups = initials.map (initial =>
input.filter (byInitial (initial))
)
const zip = (xs, ys) =>
xs.map((x, i) => [x, ys[i]])
// zip builds the pairs, where each one is the initial and the group
const grouped = zip (initials, groups)
console.log (grouped)
Using reduce, create an object with first char of each item as the key and an array of all the items which start with that char as it's value. Then call Object.entries to get the desired output:
const arr = ["apple", "orange", "avocados", "tomato", "tangerine"],
group = Object.entries(arr.reduce((a, i) => ((a[i[0]] = a[i[0]] || []).push(i), a), {}));
console.log(group);
I'm having trouble wrapping my head around this, but let's say there an array with these elements:
["apple", "banana", "pear", "kiwi", "orange"]
I would like to transfer this array into:
["apple", "apple/banana", "apple/banana/pear", "apple/banana/pear/kiwi", "apple/banana/pear/kiwi/orange"]
I need this in JavaScript and I'm not sure how to achieve it.
Please note that I'm currently working with ES5.
Here's a simple implementation of what you're trying to do :
ES5
var input = ["apple", "banana", "pear", "kiwi", "orange"];
var prev = '';
var output = input.map(function (el) {
el = prev + el; prev = el + '/'; return el;
});
console.log(output);
ES6
let input = ["apple", "banana", "pear", "kiwi", "orange"];
let prev= '';
let output = input.map( el => { el = prev + el; prev = el+'/'; return el})
console.log(output)
Array.map() is meant for these problems.
The map() method creates a new array with the results of calling a provided function on every element in the calling array.
And while walking through the array with map you can use join() and slice() to concatenate certain values from an original array.
let input = ["apple", "banana", "pear", "kiwi", "orange"];
let output = input.map((el, index) => {
return (input[index-1]) ? input.slice(0, index+1).join('/') : el;
})
output:
Array [
"apple",
"apple/banana",
"apple/banana/pear",
"apple/banana/pear/kiwi",
"apple/banana/pear/kiwi/orange"
]
Some more explanation on what is happening in those 3 lines:
// let's write it out.
let output = input.map((el, index) => {
// If there is a previous index of this array, we need to join it with this one
if (input[index-1]) {
// all previous values including this one
let a = input.slice(0, index+1)
// concatenate them all with a seperator
let b = a.join('/');
return b;
} else {
// if not just return the element
return el;
}
})
You wrote: Please note that I'm currently working with ES5.
Unfortunately, some people do not understand anymore what is ES5 and suggest ES6 solutions (with arrow function expressions, let statements and constants).
Array.map was added to the ECMA-262 standard in the ECMAScript 5.1 edition. It is fully supported by all modern browsers inclusive IE9.
var input = ["apple", "banana", "pear", "kiwi", "orange"],
output = input.map(function(elem, index)
{
return index > 0 ? input.slice(0, index + 1).join('/') : elem;
});
console.log(JSON.stringify(output, null, '\t'));
var fruits = ["apple", "pear", "orange", "banana"];
var i;
for( i=0; i<fruits.length; i++) {
if (i == 0){
continue;
}
var temp = fruits[i];
fruits[i] = fruits[i-1] + "/" + temp;
}
for( i=0; i<fruits.length; i++) {
print(fruits[i]);
}
Here you go!
Points to remember:
Concatenation Operator
For loop
continue statement
Arrays
var array = ["apple", "banana", "pear", "kiwi", "orange"]
var all = [];
var str ="";
for(var i=0;i< array.length;i++)
{
if(array[i-1]){
str += array[i-1]+'/';
all.push(str+array[i])
}
else all.push(array[i])
}
console.log(all);
Time to .reduce it
This works by creating a new array, and accessing the last placed string and appending a '/' and then the next string current.
yourArray.reduce((newArray, current) => newArray.concat(newArray.length > 0 ? newArray[newArray.length - 1] + '/' + current : current), [])
// long version:
yourArray.reduce((newArray, current) => {
if (newArray.length > 0) {
return newArray.concat(current)
} else {
const previousString = newArray[newArray.length - 1]
return newArray.concat(previousString + '/' + current)
}
}, [])
For the ones that do use ES6 or can transpile the code to ES5 (Using i.e: Babel)
const a = ["a", "b", "c", "d", "e"];
const res = a.map((_, i) => a.slice(0, i+1).join("/"));
console.log(res);
For example I have an array
let fruits = ["apple", "яблоко", "grape"]
When I do
let result = fruits.sort()
Result will be
["apple", "grape", "яблоко"]
But I want unicode items to be at the start of result array.
You can check to see if the string starts with a word character in the sort function:
const fruits = ["apple", "яблоко", "grape"];
const isAlphabetical = str => /^\w/.test(str);
fruits.sort((a, b) => (
isAlphabetical(a) - isAlphabetical(b)
|| a.localeCompare(b)
))
console.log(fruits);
A more robust sorting function would check each character against each other character:
const fruits = ["apple", "яблоко", "grape", 'dog', 'foo', 'bar', 'локоfoo', 'fooлоко', 'foobar'];
const isAlphabetical = str => /^\w/.test(str);
const codePointValue = char => {
const codePoint = char.codePointAt(0);
return codePoint < 128 ? codePoint + 100000 : codePoint;
};
fruits.sort((a, b) => {
for (let i = 0; i < a.length; i++) {
if (i >= b.length) return false;
const compare = codePointValue(a[i]) - codePointValue(b[i]);
if (compare !== 0) return compare;
}
return true;
})
console.log(fruits);