Finding letters in 2nd array element in 1st array element - javascript

Using javascript, I want to check if the string in the 1st array element contains all the letters of the 2nd array element. If so, return true. E.g. ["Mary", "Aarmy"] => true;
["hello", "hey"] => false.
I've tried the following code, which works for ["Mary", "Aarmy"] and ["voodoo", "no"], but doesn't work for ["hello", "hey"]. Appreciate any help, thanks!
function mutation(arr){
var str1 = arr.pop().toLowerCase();
var str2 = arr.pop().toLowerCase();
for(var i = 0; i < str2.length; i++){
if(str1.indexOf(str2[i]) !== -1){
return true;
}
else return false;
}
}

When you use pop() it'll return the last element in the array and not the first.
Also your if else is inside for and has a return statement. This does not let the for loop run completely and returns after the very first loop.
function mutation(arr){
var str2 = arr.pop().toLowerCase();
var str1 = arr.pop().toLowerCase();
console.log("str1: " + str1);
console.log("str2: " + str2);
for(var i = 0; i < str2.length; i++){
if(str1.indexOf(str2[i]) === -1){
return false;
}
}
return true;
}
arr = ["hello", "hey"];
console.log(mutation(arr));
arr = ["Mary", "Aarmy"];
console.log(mutation(arr));

Considering you can use Set, and lodash, here is another solution:
const _ = require("lodash");
function mutation(arr) {
var set1 = new Set(arr.pop().toLowerCase().split(''));
var set2 = new Set(arr.pop().toLowerCase().split(''));
return _.isEqual(set1, set2);
}
console.log(mutation(["Mary", "Aarmy"])); //true
console.log(mutation(["hello", "hey"])); //false
console.log(mutation(["voodoo", "no"])); //false
Check the working sample: https://jsfiddle.net/sayan751/3q8rtqy3/

Recursively, just for sport. If you're dealing with long (>100 char) strings, this is risky, as it relies on stack space.
const contains = function (a, b) {
if (!b) return true;
return a.indexOf(b[0]) !== -1 && contains(a, b.substring(1));
}
console.log(contains('mary', 'army')); // true
console.log(contains('hello', 'hey')); // false

Split and sort to speed up things - now only ONE comparison per set
var arr = ["Mary", "Aarmy","hello", "hey", "voodoo", "no"]
function mutation(){
var str1 = arr.pop().toLowerCase().split("").sort().join("");
var str2 = arr.pop().toLowerCase().split("").sort().join("");
return str1.indexOf(str2) !=-1;
}
while (arr.length) console.log(arr[arr.length-2],mutation())

How could function return more than one value ;) (line 6) And if second array has an array length of 3 it just checks the first arrays 3 elements. (line 4)

function mutation(arr) {
var set1 = arr[0].toLowerCase();
var set2 = arr[1].split('');
return set2.every(function(element, index, array){
if(set1.indexOf(element.toLowerCase()) != -1)
return true;
else
return false;
});
}
console.log(mutation(["Mary", "Aarmy"])); //return true
console.log(mutation(["hello", "hey"])); //return false
console.log(mutation( ["voodoo", "no"])); //return false
console.log(mutation( ["voodoo", "vo"])); //return true

Related

Compare Two Array in Javascript/AngularJS

I want to check two array values are same or not. I am using a form with checkboxes. need show any change in checkbox array or not?. can anyone help me. Two arrays Like this.
array1 = ['1','2','3']; //previous checklist
array2 = ['3','2','1']; //new checklist
Here is a snippet that compares two arrays.
var array1 = [1,2,3];
var array2 = [1,2,3];
var result = array1.length == array2.length && array1.every(function(element, index) {
return element === array2[index];
});
alert(result);
however 1,2,3 in one array is not equal with 3,2,1 in another. You didn't mentioned about to check the array elements or just the array !
In Case you need to compare two arrays with different positions, try this
var array1=[1,2,3,4]
var array2=[1,4,3,2]
var result = array1.length==array2.length && array1.every(function(v,i) { return ($.inArray(v,array2) != -1)})
console.log(result)
I got this:
let arr = ['1', '2', '3'];
let arr2 = ['3', '1', '2'];
let finalResult = arr.length === arr2.length;
arr.forEach(function (item) {
if (!finalResult) {
return;
}
if (arr2.find(function (item2) { return item === item2; }) === undefined) {
finalResult = false;
}
});
console.log(finalResult);
// Warn if overriding existing method
if(Array.prototype.equals)
console.warn("Overriding existing Array.prototype.equals. Possible causes: New API defines the method, there's a framework conflict or you've got double inclusions in your code.");
// attach the .equals method to Array's prototype to call it on any array
Array.prototype.equals = function (array) {
// if the other array is a falsy value, return
if (!array)
return false;
// compare lengths - can save a lot of time
if (this.length != array.length)
return false;
for (var i = 0, l=this.length; i < l; i++) {
// Checking whether the array contains this element
if(isValueExistsInArray(this[i],array) == false) {
return false;
}
}
return true;
}
function isValueExistsInArray(value,compareToArray) {
for(var j = 0, k=compareToArray.length; j<k; j++) {
if(value == compareToArray[j]) {
return true;
}
}
return false;
}
// Hide method from for-in loops
Object.defineProperty(Array.prototype, "equals", {enumerable: false});
array1 = ['1','2','3'];
array2 = ['1','2','3'];
array3 = ['3','2','1'];
array4 = ['3','5','1'];
array5 = ['3','5','1',6];
array1.equals(array2) == true
array1.equals(array3) == true
array1.equals(array4) == false
array1.equals(array5) == false
Finally I have perfect answer for compare two array in javascript.
var array1 = ["1","2","3"];
var arr1 = array1.map(function (x) {
return parseInt(x, 10);
});
var array2 = ["3","2","1"];
var arr2 = array2.map(function (x) {
return parseInt(x, 10);
});
var finalArray1 = arr1.sort();
var finalArray2 = arr2.sort();
var is_same = finalArray1.length == finalArray2.length && finalArray1.every(function(element, index) {
return element === finalArray2[index];
});
if(is_same == true){
console.log('match');
}else{
console.log('not match');
}

Remove Duplicates from Jquery

I have two strings like below and I need to remove the duplicates.
I.E., I need to remove/ignore the common elements in both the strings and show only the difference.
var char1 = "AAA-BBB|BBB-CCC|CCC-AAA";
var char2 = "AAA-BBB|BBB-CCC";
var removeDuplicates = //<-- Here I need CCC-AAA only
Here I have tried it,
var Joined = char1 + "|" + char2;
var removeDuplicates = $.unique(Joined.split('|')); //<-- Result : "AAA-BBB|BBB-CCC|CCC-AAA";
jQuery's $.grep can be used to remove all duplicates in an array
var char1 = "AAA-BBB|BBB-CCC|CCC-AAA";
var char2 = "AAA-BBB|BBB-CCC";
var removeDuplicates = $.grep(char1.split('|'), (function(y) {
return function(item) { return $.inArray(item, y) === -1 }
})(char2.split('|')));
console.log( removeDuplicates );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You can simply make an array from the parameters and Array#filter() the array one returning only the elements that are not in the second array with Array#indexOf():
var char1 = "AAA-BBB|BBB-CCC|CCC-AAA",
char2 = "AAA-BBB|BBB-CCC",
removeDuplicates = function(str1, str2) {
var arr1 = str1.split('|'),
arr2 = str2.split('|');
return arr1.filter(function(item) {
return arr2.indexOf(item) === -1;
});
};
console.log(removeDuplicates(char1, char2));

Find the Words with an even number of occurrences in an Array - Javascript

Given an array of words, write a function that returns an array of the words that occur an even number of times.
function even(["hello", "hi", "hello", "elephant", "hi"]);
That output should be:
["hello", "hi"]
This has been a toy problem I have been struggling with recently. I have solved similar problems counting and returning the number of occurrences of elements in an array but am having trouble taking that logic and applying it to this problem.
This is what I have tried so far, but have hit a wall when trying to output just the even occurrences:
function even(collection) {
var results = [];
for(var i = 0; i < collection.length; i++){
var value = collection[i];
if(results[value]){
results[value] = results[value] + 1;
}else{
results[value] = 1;
}
}
return results;
}
You can use reduce to get an actual count of the words, then simply return an array of the ones that have an even count:
function even(wordsArr) {
//Object of words and counts
var wordCounts = wordsArr.reduce(function(counts, word) {
if (!counts.hasOwnProperty(word)) {
counts[word] = 0;
}
counts[word]++;
return counts;
}, {});
//Now filter that out and return
return Object.keys(wordCounts).filter(function(word) {
return wordCounts[word] % 2 === 0
});
}
even(["hello", "hi", "hello", "elephant", "hi"]); //["hello", "hi"]
var arr = ["hello", "hi", "hello", "elephant", "hi"];
function onlyEvens( arr )
{
var countObj = {};
for( var i = 0; i < arr.length; i++ )
{
var item = arr[i];
if( countObj[ item ] !== undefined )
countObj[item]++;
else
countObj[item] = 1;
}//for()
var filteredArray = [];
for(var key in countObj )
{
if( countObj[key] % 2 == 0 )
filteredArray.push( key );
}
return filteredArray;
}//onlyEvens()
console.log( onlyEvens( arr ) );
Issues in your code:
you use collection instead of words
you cannot access array the associative way. You must declare it as object:
results[value]
you return result variable, but it is undeclared.
return result;
results only contains the occurrences of every word. There miss the code that calculates if the occurrences of a word are odd or even.
fixed code:
function even(words) { // <<< in your code was collection
var results = {};
for(var i = 0; i < words.length; i++){
var value = words[i];
if(results[value]){
results[value] = results[value] + 1;
}else{
results[value] = 1;
}
}
var ret = [];
for(var word in results)
if(results[word]%2 !== 0)
rest.push(word);
return ret;
}
function even(list) {
var d = list.reduce(function(d, w) { d[w] = !d[w]; return d; }, {});
return Object.keys(d).filter(function(w) { return !d[w]; });
}
console.log(even(["hello", "hi", "hello", "elephant", "hi"]));
console.log(even(["hello", "yo", "yo", "hi", "hello", "yo", "elephant", "hi"]));
Explanation: Use the array .reduce() method to create an object (d) with a property for each word (w) with a boolean value indicating whether the word has an odd number of occurrences. Then .filter() the keys to get all the ones that are not odd.
If you previously sort the array you can filter it as required in just a code line like this :
var even = (str) => str.sort().filter((element, index, arr) => index+1 === arr.lastIndexOf(element));
console.log(even(["hello", "hello", "hi", "elephant", "hi", "hi"])); //[ 'hello', 'hi' ]

Match one of the elements of an array in a string using javascript

I'm trying to create a function that returns true if at least one of the elements of a string array is found within another string.
function findInString(str) {
var fruits = ["orange", "banana", "grape"];
for(var i = 0; i < fruits.length; i++) {
if (str.indexOf(fruits[i]) > -1) {
return true;
}
}
return false;
}
var a = findInString("I love orange juice."); //=> returns true
var b = findInString("I don't like peach."); //=> returns false
This function does the trick, but I'm sure there might some array or string method that does the same without having to loop through the array. Any ideas?
Thanks.
You could use some which comes very close to this. Here's how I'd write it:
function find (str, arr) {
return arr.some((s) => s.indexOf(str) > -1);
}
You could do this as well if you'd like but I don't feel good about it.
function find (str, arr) {
return arr.join(',').indexOf(str) > -1
}
You can use some function.
function findInString(str, arr) {
return arr.some(function(el) {
return str.indexOf(el) > -1;
});
}
var fruits = ["orange", "banana", "grape"];
var a = findInString("I love orange juice.", fruits); //=> returns true
var b = findInString("I don't like peach.", fruits); //=> returns false
I think you do have to process the array. I would make two changes.
First I would pass in the array as well as the string, making a generic function, then I would rework it so that once it finds one it quits doing that and exits the loop; similar concept as the return true but just a differing way to do it - my personal preference to only have one function exit.
function findInString(arr, str) {
var hasString = false;
for (var i = 0; i < fruits.length; i++) {
if (str.indexOf(fruits[i]) > -1) {
hasString = true;
break;
}
}
return hasString;
}
var fruits = ["orange", "banana", "grape"];
var a = findInString(fruits, "I love orange juice."); //=> returns true
var b = findInString(fruits, "I don't like peach."); //=> returns false
I like your way of doing it. I got a little into it, here are several ways you can think about doing this:
Some of these are really close, but that last period might require some string parsing to handle every case. Note the last one, since it uses RegExp, wont require doing anything to the string:
JsBin Example
function findInString(str) {
var fruits = ["orange", "banana", "grape"];
return str.split(' ').filter(function(el) {
return fruits.indexOf(el) > -1;
}).length > 0;
}
function finderWithReduce(str) {
var fruits = ["orange", "banana", "grape"];
var result = false;
str.split(' ').reduce(function(a, b) {
if (a.indexOf(b) > -1) {
result = true;
}
return a;
}, fruits);
return result;
}
function finderWithForEach(str){
var fruits = ["orange", "banana", "grape"];
var result = false;
fruits.forEach(function(fruit) {
if (str.indexOf(fruit) > -1) {
result = true;
}
});
return result;
}
function finderWithRegex(str) {
var fruits = ["orange", "banana", "grape"];
for (var i = 0; i < fruits.length; i++) {
var re = new RegExp(fruits[i], 'gi');
if (str.match(re) !== null) {
return true;
}
}
return false;
}
Here's a functional ES6 method. presentIn is a higher-order function that takes a string and returns a function that acts as the some callback.
const presentIn = (str) => (el) => str.includes(el);
fruits.some(presentIn('I love orange juice.')); // true
fruits.some(presentIn('I don\'t like peach.')); // false
I really like this approach because you're operating directly on the array elements, and if you name your function well it scans brilliantly: "Are some elements of the array present in the string".
DEMO
The slightly more verbose ES5 version for comparison:
function presentIn(str) {
return function (el) {
return str.indexOf(el) > -1;
}
}
Conceptually I can't think of a better (or even different) way of doing this. I don't know of a built in function which performs this task but even if there was one it's implementation would be this anyway.

how to cut a string in javascript

I'm receiving a String like this:
"45,21,555,64,94,796,488,\n " the \n means new line
is there a way to cut the string based on "," and getting only the "number".
I could do it C but how can I search for a character in JavaScript.
thanks for any hint
var parts = "45,21,555,64,94,796,488,\n ".split(',').filter(function(val) {
var num = parseInt(val, 10);
return !isNaN(num) && toString.call(num) === '[object Number]';
});
// parts: ["45", "21", "555", "64", "94", "796", "488"]
This is taking your String and splitting it into an Array based on a delimiter (',') and then running it through a filter function to remove anything that does not evaluate to a valid Number.
See String.prototype.split and Array.prototype.filter.
If you actually want to then convert those values to Numbers, you could chain a map call:
var parts = "45,21,555,64,94,796,488,\n ".split(',')
.filter(function(val) {
var num = parseInt(val, 10);
return !isNaN(num) && toString.call(num) === '[object Number]';
})
.map(function(val) {
return parseInt(val, 10);
});
// parts: [45, 21, 555, 64, 94, 796, 488]
Yes, like this:
var myString = "45,21,555,64,94,796,488,\n ";
var splitStrings = string.split(",");
console.log(splitStrings); //Should log an array to the console, containing only your strings e.g. [45,21,555,64,94,796,488,\n]
This returns an array of strings, split by the character you passed in. You can read more on this method here: http://www.w3schools.com/jsref/jsref_split.asp
After that, you can parse your array to remove anything you don't want like the new line character, or use a filter method to do it inline as detailed in another answer
You can use string.split(splitChar) to split. Then you can use .map or .filter to convert items to number.
var str = "45,21,555,64,94,796,488,\n ";
var arr = str.split(",");
document.write("Array: <pre>"+JSON.stringify(arr)+"</pre>");
var nums = arr.map(function(item){
return parseInt(item);
});
document.write("Numbers: <pre>"+JSON.stringify(nums)+"</pre>");
If you are wanting just the numbers as an array you could do this.
var str = "45,21,555,64,94,796,488,\n ";
var arr = str.split(","); //Make the string into an array
var len = arr.length;
for(var i=0;i<len;i++)
{
try
{
arr[i] = parseInt(arr[i]); // convert the numbers to ints
}
catch(e)
{
arr[i] = null;
}
}
As the fact that strings are just arrays, you can do it this way (a bit more comprehensive, in my opinion):
function noCommas(a)
{
var b = '';
for (var i = 0; i < a.length; i++)
{
if (a[i] != ',') //&& a[i]!= String.fromCharCode(10)) If you want no new lines too
{
b += a[i];
} else
{
//break; -> In case you only want the first value
}
}
return parseInt(b); //To return the value as an integer
}
noCommas('1234,6789'); // returns 12346789
I missunderstood the question, so here's my fixed code:
function noCommas(a)
{
var b = [];
var tempNum = '';
for (var i = 0; i < a.length; i++)
{
if (a[i] != ',' && i != a.length - 1)
{
tempNum += a[i];
} else
{
b.push(parseInt(tempNum))
tempNum = '';
}
}
return b;
}
now if you do noCommas('123,345,324234')[2] it would return 324234.

Categories