unexpected results which is empty array - javascript

when I run code, I see empty array, but I aim to have an array with some vowels.
let input = 'zai';
const vowels = ['a', 'u', 'o', 'e', 'i'];
let resultArray = [];
for (let inputindex = 0; inputindex < input.inputindex; inputindex++) {
for (let vowel = 0; vowel > vowels.length; vowel++) {
if (input[inputindex] === vowels[vowel]) {
resultArray.push(input[inputindex])
}
}
}
console.log(resultArray)

You have done a mistake by writing input.inputindex instead of input.length. Plus, you have wrote vowel > vowel.length instead of vowel < vowels.length. That's why your loop didn't run at least a single loop and ended up with an empty array. Correct the code as below and try again...
let input = 'zai';
const vowels = ['a', 'u', 'o', 'e', 'i'];
let resultArray = [];
for (let inputindex = 0; inputindex < input.length; inputindex++) {
for (let vowel = 0; vowel < vowels.length; vowel++) {
if (input[inputindex] === vowels[vowel]) {
resultArray.push(input[inputindex])
}
}
}
console.log(resultArray)

input string but you need array, i use split.
and some mistakes in loops
let input = 'zai';
let input2 = input.split('')
const vowels = ['a', 'u', 'o', 'e', 'i'];
let resultArray = [];
for(let inputindex = 0; inputindex < input2.length; inputindex++){
for(let vowel = 0; vowel < vowels.length; vowel++){
if(input2[inputindex] === vowels[vowel]){
resultArray.push(input2[inputindex])
}
}
}
display.log(resultArray)
Without array
let input = 'zai';
const vowels = ['a', 'u', 'o', 'e', 'i'];
let resultArray = [];
for(let inputindex = 0; inputindex < input2.length; inputindex++){
for(let vowel = 0; vowel < vowels.length; vowel++){
if(input.slice(inputindex, inputindex+1) === vowels[vowel]){
resultArray.push(input.slice(inputindex, inputindex+1))
}
}
}
display.log(resultArray)

looping through the inputs and comparing them with each value in vowels using the .some method as so:
let input = 'zai';
let vowels = ['a', 'u', 'o', 'e', 'i'];
let resultArray = [];
for (let inputindex = 0; inputindex < input.length; inputindex++) {
if (vowels.some(v => v === input[inputindex])) {
resultArray.push(input[inputindex])
}
}
console.log(resultArray)

Related

Printing elements that don't satisfy condition

I'm trying to complete a HackerRank challenge that involves printing a list of elements of an array starting with all the vowels then all the consonants but I'm having trouble with that.
function vowelsAndConsonants(s) {
var str = s;
var arr = str.split("");
var i;
var vow = ["a","e","i","o","u","y"];
var con = ['b','c','d','f','g','h','j','k','l','m','n','p','q','r','s','t','v','w','x','z']
for (i = 0; i < arr.length; i++) {
for (var j = 0; j< vow.length; j++){
if (arr[i] === vow[j]){
console.log(arr[i])
}
}
}
}
This is what I get from the code above, but I can't print the consonants. The input string is "javascriptloops"
a
a
i
o
o
I also tried this
function vowelsAndConsonants(s) {
var str = s;
var arr = str.split("");
var i;
var vow = ["a","e","i","o","u","y"];
var con = ['b','c','d','f','g','h','j','k','l','m','n','p','q','r','s','t','v','w','x','z']
for (i = 0; i < arr.length; i++) {
for (var j = 0; j< vow.length; j++){
if (arr[i] === vow[j]){
console.log(arr[i])
break;
}
}
for (var j = 0; j< con.length; j++){
if (arr[i] === con[j]){
console.log(arr[i])
}
}
}
}
But here's what I had
j
a
v
a
s
c
r
i
p
t
l
o
o
p
s
An easy solution would be looping through twice:
function vowelsAndConsonants(s) {
let vowels = ["a", "e", "i", "o", "u"];
for(let v of s) {
if(vowels.includes(v))
console.log(v);
}
for(let v of s) {
if(!vowels.includes(v))
console.log(v);
}
}
It's a good idea to define the smaller subset (vowels) and treat the rest of the letters of the alphabet as consonants.
Also, naming your variables goes a long way in readability
function vowelsAndConsonants(s) {
var letters = s.split("");
const vowels = ["a", "e", "i", "o", "u", "y"];
for (const letter of letters) { // we are cycling through the letters to find all vowels
for (const vowel of vowels) { // now we are cycling through the list of vowels
if (letter === vowel) { // if we found a vowel in the vowel list, print it and stop searching for other vowels (break)
console.log(letter);
break;
}
}
}
// Searching for consonants is trickier
for (const letter of letters) { // we cycle again through the letters
let consonant = true; // we assume that the letter is consonant until it's proven otherwise
for (const vowel of vowels) { // cycling through the list of vowels
if (letter === vowel) { // if we found that the letter is vowel
consonant = false; // we set the flag to false
break; // and stop searching more as we know already that it is a vowel
}
}
if (consonant === true) { // if after cycling we realized that this is a consonant, and not a vowel - print it
console.log(letter)
}
}
}
vowelsAndConsonants("normal");
there is a solution, you can take a look
function vowelsAndConsonants(s) {
var str = s;
var arr = str.split("");
var vow = ["a","e","i","o","u","y"];
const ordered = arr.reduce( (res, letter) => {
if (vow.includes(letter)) {
return {...res, vow: [...res.vow, letter]}
}
return {...res, con: [...res.con, letter]}
}, { con: [], vow: []});
return ordered.vow.join('') + ordered.con.join('');
}
Your outer loop needs to run twice.
This solution also uses for ... in loops and array.includes(), which is a little cleaner than nesting standard for loops.
const vowelsAndConsonants = s => {
const vow = ['a','e','i','o','u','y'];
for (const c of s)
if (vow.includes(c))
console.log(c)
for (const c of s)
if (!vow.includes(c))
console.log(c)
}
vowelsAndConsonants('javascriptloops')
You can use filter() instead of loops:
var vow = ['a','e','i','o','u','y'].join('');
var str = 'javascriptloops'.split('');
console.log(str.filter(x => vow.includes(x))); // vowels
console.log(str.filter(x => !vow.includes(x))); // consonants (not vowels)
const f = s => {
const isVowel = char => ['a', 'e', 'i', 'o', 'u'].includes(char);
const letters = s.split('');
const consonants = letters.reduce((result, letter) => {
if (isVowel(letter)) console.log(letter);
else result.push(letter);
return result;
}, []);
consonants.forEach(c => console.log(c))
}
f('javascriptloops');

How to write a Javascript function to get all palindromic subsequences from string in order?

A subsequence is a group of characters chosen from a list while maintaining their order. For instance, the subsequenes of the string abc are [a, b, c, ab, ac, bc, abc].
Now, I need to write a function to return all the palindromic subsequences from a given string in order. For instance, for the string acdapmpomp, the output should be [a,c,d,p,m,o,aa,aca,ada,pmp,mm,mom,pp,ppp,pop,mpm,pmpmp].
My code is:
function getAllPalindromicSubsequences(str) {
var result = [];
for (let i = 0; i < str.length; i++) {
for (let j = i + 1; j < str.length + 1; j++) {
if (str.slice(i, j).split("").reverse().join("") == str.slice(i, j)){
result.push(str.slice(i, j));
}
}
}
return result;
}
console.log(getAllPalindromicSubsequences("acdapmpomp"));
But this produces the following output:
[
'a', 'c', 'd',
'a', 'p', 'pmp',
'm', 'p', 'o',
'm', 'p'
]
What is the mistake I am making? And what should be the correct code?
You could take a recursive approach and collect all character and check is they are palindromes.
function getSub(string) {
function isPalindrome(string) {
let l = 0,
r = string.length - 1;
if (!string) return false;
while (l < r) {
if (string[l] !== string[r]) return false;
l++; r--;
}
return true;
}
function sub([character, ...rest], right = '') {
if (isPalindrome(right) && !result.includes(right)) result.push(right);
if (!character) return;
sub(rest, right + character);
sub(rest, right);
}
var result = [];
sub([...string])
return result;
}
console.log(getSub('acdapmpomp'));

Find all sets of length n combinations of m arrays

Objective: Find all sets of length n combinations of m arrays, such that index i of each item in a set is not the same as i in any other element of that set
I have the following arrays:
array1 = ['a', 'b', 'c', 'd'];
array2 = ['e', 'f', 'g', 'h'];
array3 = ['i', 'j', 'k', 'l'];
array4 = ['m', 'n', 'o', 'p'];
I would like to find every possible combination of these taking one element from each array, but then place those combinations into sets such that index i of any element in a given set is different to index i of another element in that same set. For instance, one set could be:
[
{ 1: "a", 2: "e", 3: "i", 4: "m" },
{ 1: "b", 2: "f", 3: "j", 4: "n" },
{ 1: "c", 2: "g", 3: "k", 4: "o" },
{ 1: "d", 2: "h", 3: "l", 4: "p" }
]
as every property '1' is different and taken from array1, every property '2' is different and taken from array2, etc.
Now I need to find every possible one of these.
I've tried looking at this post and implement it by creating combinations of combinations before filtering out everything invalid and cycling through to establish sets, but of course this missed many and took almost an hour to run on this example. Therefore, I need a more systematic approach to speed up the process and make it neater.
You basically want to find every permutation of every array and combine them. This can be done recursively:
function permutate(arr) {
// every array of length one is already permutated
if (arr.length == 1) return [ arr ];
let permutations = [];
for (let i = 0; i < arr.length; i++) {
// Remove the current element and permutate the rest
let sub = permutate(arr.splice(i, 1));
// Insert current element into every permutation
sub = sub.map(x => [arr[i], ...x]);
// Add permutations to list
permutations.push(...sub);
}
return permutations;
}
Next the combine function:
function combine(arrays, current = [], i = 0) {
if (i == arrays.length)
return [ current ];
let values = [];
for (let j = 0; j < arrays[i].length; j++) {
let temp = current.slice();
temp.push(arrays[i][j]);
values.push(...combine(arrays, temp, i + 1));
}
return values;
}
// If you get a call stack size exceeded (stackoverflow) error, you can replace
// this using nested for loops. For instance for 5 arrays with 5 elements each:
let sets = [];
for (let i = 0; i < permutations[0].length; i++) {
for (let j = 0; j < permutations[1].length; j++) {
for (let k = 0; k < permutations[2].length; k++) {
for (let l = 0; l < permutations[3].length; l++) {
for (let m = 0; m < permutations[4].length; m++) {
let set = [];
for (let n = 0; n < 5; n++) {
set.push([ permutations[0][i][n], permutations[1][j][n], permutations[2][k][n], permutations[3][l][n], permutations[4][m][n] ]);
}
sets.push(set);
}
}
}
}
}
By first permutating every array (which results in 24 different permutations for each one), then combining these (which is 24^4=331776 combinations), you'll get everything you need to construct the arrays. Just loop over every combination and put the elements at the same indices into the same set:
let permutations = [ array1, array2, array3, array4 ].map(arr => permutate(arr));
let sets = combine(permutations);
let out = [];
for (let i = 0; i < sets.length; i++) {
let set = [];
for (let j = 0; j < 4; j++) {
set.push([ sets[i][0][j], sets[i][1][j], sets[i][2][j], sets[i][3][j] ]);
}
out.push(set);
}
Working example:
array1 = ['a', 'b', 'c', 'd'];
array2 = ['e', 'f', 'g', 'h'];
array3 = ['i', 'j', 'k', 'l'];
array4 = ['m', 'n', 'o', 'p'];
function permutate(arr) {
if (arr.length == 1) return [ arr ];
let permutations = [];
for (let i = 0; i < arr.length; i++) {
let temp = arr.slice();
temp.splice(i, 1);
let sub = permutate(temp);
sub = sub.map(x => [arr[i], ...x]);
permutations.push(...sub);
}
return permutations;
}
function combine(arrays, current = [], i = 0) {
if (i == arrays.length)
return [ current ];
let values = [];
for (let j = 0; j < arrays[i].length; j++) {
let temp = current.slice();
temp.push(arrays[i][j]);
values.push(...combine(arrays, temp, i + 1));
}
return values;
}
let permutations = [ array1, array2, array3, array4 ].map(arr => permutate(arr));
console.log(permutations);
let sets = combine(permutations);
let out = [];
for (let i = 0; i < sets.length; i++) {
let set = [];
for (let j = 0; j < 4; j++) {
set.push([ sets[i][0][j], sets[i][1][j], sets[i][2][j], sets[i][3][j] ]);
}
out.push(set);
}
console.log(out);

Getting an array result not in order

function pairElement(str) {
var arr = [['G','C'],['C','G'],['A','T'],['T','A']],b=[]
for(var k=0;k<arr.length;++k){
var res = arr.filter(function(v){
return v;
})[k][0]
var j=0;
while(j<str.length){
if(str[j]===res){
b.push(arr[k])
}
j++;
}
}
return b;
}
console.log(pairElement("ATCGA"));
I want pairing result in order of the argument passed to the main function. This code's result should be
[['A','T'],['T','A'],['C','G'],['G','C'],['A','T']] but i'm getting as [['G','C'],['C','G'],['A','T'],['A','T'],['T','A']]
Your inner and outer loops are flipped. The outer loop should iterate over the string, and the inner loop should iterate over the array.
function pairElement(str) {
var arr = [['G', 'C'], ['C', 'G'], ['A', 'T'], ['T', 'A']],
b = [];
for (var k = 0; k < str.length; k++) {
for (var j = 0; j < arr.length; j++) {
if (str[k] === arr[j][0]) {
b.push(arr[j]);
}
}
}
return b;
}
console.log(pairElement("ATCGA"));
Your code can also be simplified using an object instead of a 2D array, and with Array#map:
function pairElement(str) {
var pairs = { 'G': 'C', 'C': 'G', 'A': 'T', 'T': 'A' };
return str.split('').map(ch => [ch, pairs[ch]]);
}
console.log(pairElement("ATCGA"));

Compare two Javascript Arrays and remove Duplicates

It is working well is there any other better way to remove duplicates from one array if it has elements of another array ?.
<script>
var array1 = new Array("a","b","c","d","e","f");
var array2 = new Array("c","e");
for (var i = 0; i<array2.length; i++) {
var arrlen = array1.length;
for (var j = 0; j<arrlen; j++) {
if (array2[i] == array1[j]) {
array1 = array1.slice(0, j).concat(array1.slice(j+1, arrlen));
}
}
}
alert(array1);
</script>
array1 = array1.filter(function(val) {
return array2.indexOf(val) == -1;
});
Or, with the availability of ES6:
array1 = array1.filter(val => !array2.includes(val));
filter() reference here
indexOf() reference here
includes() reference here
The trick, for reasons that are beyond me, is to loop the outer loop downwards (i--) and the inner loop upwards (j++).
See the example bellow:
function test() {
var array1 = new Array("a","b","c","d","e","f");
var array2 = new Array("c","e");
for (var i = array1.length - 1; i >= 0; i--) {
for (var j = 0; j < array2.length; j++) {
if (array1[i] === array2[j]) {
array1.splice(i, 1);
}
}
}
console.log(array1)
}
How do I know this? See the below:
for( var i =myArray.length - 1; i>=0; i--){
for( var j=0; j<toRemove.length; j++){
if(myArray[i] === toRemove[j]){
myArray.splice(i, 1);
}
}
}
or
var myArray = [
{name: 'deepak', place: 'bangalore'},
{name: 'chirag', place: 'bangalore'},
{name: 'alok', place: 'berhampur'},
{name: 'chandan', place: 'mumbai'}
];
var toRemove = [
{name: 'deepak', place: 'bangalore'},
{name: 'alok', place: 'berhampur'}
];
for( var i=myArray.length - 1; i>=0; i--){
for( var j=0; j<toRemove.length; j++){
if(myArray[i] && (myArray[i].name === toRemove[j].name)){
myArray.splice(i, 1);
}
}
}
alert(JSON.stringify(myArray));
On that note, would anyone be able to explain why the outer loop needs to be looped downwards (--)?
Good luck!
Using the Set.prototype Constructor: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set
let array1 = Array('a', 'b', 'c', 'd', 'e', 'f')
let array2 = Array('c', 'e', 'g')
let concat = array1.concat(array2) // join arrays => [ 'a', 'b', 'c', 'd', 'e', 'f', 'c', 'e', 'g' ]
// Set will filter out duplicates automatically
let set = new Set(concat) // => Set { 'a', 'b', 'c', 'd', 'e', 'f', 'g' }
// Use spread operator to extend Set to an Array
let result = [...set]
console.log(result) // => [ 'a', 'b', 'c', 'd', 'e', 'f', 'g' ]
You can try this
array1 = array1 .filter(val => {
return !array2.find((val2)=>{
// console.log({valueID:val.id+":"+val2.id});
return val.id===val2.id
})
});
use Array.splice()
var array1 = ['1', '2', '3', '4', '5'];
var array2 = ['4', '5'];
var index;
for (var i=0; i<array2.length; i++) {
index = array1.indexOf(array2[i]);
if (index > -1) {
array1.splice(index, 1);
}
}
This my solution
array1 = array1.filter(function(val) {
return array2.indexOf(val.toString()) == -1;
});
This is my solution to remove duplicate in ES6.
let foundDuplicate = false;
existingOptions.some(existingItem => {
result = result.filter(item => {
if (existingItem.value !== item.value) {
return item;
} else {
foundDuplicate = true;
}
});
return foundDuplicate;
});
I used this approach because in my case I was having array of objects and indexOf was having problem with it.
window.onload = function () {
var array1 = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm'];
var array2 = ['c', 'h', 'k'];
var array3 = [];
var SecondarrayIndexcount = 0;
for (var i = 0; i < array1.length; i++) {
for (var j = 0; j < array2.length; j++) {
if (array1[i] !== array2[j]) {
if (SecondarrayIndexcount === (array2.length - 1)) {
array3.push(array1[i]);
SecondarrayIndexcount = 0;
break;
}
SecondarrayIndexcount++;
}
}
}
for (var i in array3) {
alert(array3[i]);
}
}
</script>

Categories

Resources