How to compare a text with array elements? - javascript

I am working on the following demo. How can I do an exact comparison between test and elements in an array arr1?
var arr1 = ['noël','noel'];
var test = 'noel;
if(){
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

If you're attempting to determine if test is included in arr1, you may simply:
if (arr1.indexOf(test) >= 0) {
// Test is in arr1!
}
The indexOf function returns the index location of an item if it's contained in an array, and -1, if it's not in the array.

if(arr1.includes(test)){
//Stuff happens
};
This should do the trick.

syntax error at var test='noel';
if you are to extract the differences you can use this
var arr1 = ['noël','noel'];
var test = 'noel';
arr1.forEach(function(element)
{
element==test?null:console.log(element);
});

Related

An if loop omitting an array

I have an array of strings like thisvar arr = ['BUTTON','BADGE','CHECKBOX]'
Now I need a if condition to be written for the strings except those present in the array. How do I do that??
I'm a beginner and know nothing much about javascript. Thanks in advance for your help.
I tried var arr = ['BUTTON','BADGE','CHECKBOX];
if(!arr){
//code to be executed
}
However this always returns false.
You can use indexOf:
if(arr.indexOf(test_variable) === -1){
// element doesn't exist in array
}
I don't really understand your question but maybe array.some can solve your problem:
var someString = 'BADGE';
var arr = ['BUTTON','BADGE','CHECKBOX' ];
if (arr.some(str => str === someString)) {
console.log("Exist");
} else {
console.log("Doesn't exist");
}
This is how to do it:
var pippo = "pippo";
var arr = ['BUTTON','BADGE','CHECKBOX'];
if(arr.indexOf(pippo) > -1){
console.log("contained!");
}
else{
console.log("not contained!");
}
First of all the last element of your array/list is not properly written as a string i.e 'CHECKBOX. You missed a single quote in the end so it should be 'CHECKBOX'
var arr = ['BUTTON','BADGE','CHECKBOX];
↓
var arr = ['BUTTON','BADGE','CHECKBOX'];
Secondly coming to your actual query, according to your question it seems you want to run a piece of code if a string is not present in the array.
For this, you can use the array.indexOf() function which returns the position/index of the variable in the array passed as a parameter to it & if the variable is not present in the array, it returns a value of -1
More about this:- https://www.w3schools.com/jsref/jsref_indexof_array.asp
So the code for that would be:-
var arr = ['BUTTON','BADGE','CHECKBOX'];
var str = 'foo'; //string not present in the array i.e arr
if(arr.indexOf(str) === -1) {
//your code here
}
length will works for you if comes 0, return 0 when not element exists in the arrayset
var arr = ['BUTTON','BADGE','CHECKBOX'];
console.log(arr.length)

Removing an element from a javascript array causing issues

So I'm a little stuck as to why this isn't working. I'm trying to remove all of the empty strings in an array and it keeps giving me back an array that is just one empty string. Any ideas?
function splitNames(){
var names = document.getElementById("1").value.split("\n");
for(var i = 0; i<=names.length; i++){
if(names[i]==""){
names = names.splice(i, 1);
console.log(names);
}
}
console.log(names);
}
The string would look like this by the way.
Hi
Hello
(remove this one)
Bonjour
blah
(remove this one)
(remove this one)
blah
The array comes out to this ["Hi", "Hello","",...]
Perhaps the simplest way to do this is to use the filter function and search for truthy values. By default, empty strings are false.
The filter() method creates a new array with all elements that pass the test implemented by the provided function.
var strings = ["zebras", "trees", "forests", "", "hi", "wizards", "", "", "lizards"];
strings = strings.filter((e) => e);
console.log(strings);
It's important to note that empty strings by default are false. However, strings that contain only whitespace characters are true. In that scenario, my example would not work and you would have to do this
strings.filter((e) => e.trim());
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
function splitNames(){
// var names = document.getElementById("1").value.split("\n");
var names = "Hi\nHello\n \nGoodBye".split("\n");
var filteredNames = names.filter(function(item){
return item.trim() !== "";
});//filter
return filteredNames;
}//splitNames()
console.log( splitNames() );
Create a new array and push what you need.
function splitNames(){
var names = document.getElementById("1").value.split("\n");
var newArr = [];
for(var i = 0; i<=names.length; i++){
if(names[i]){
newArr.push(names[i]);
}
}
return newArr.join('\n');
//console.log(names);
}
try it:
function splitNames(){
var names = document.getElementById("1").value.split("\n");
var newArr = names.filter(function(name){
return name!=="";
});
return newArr;
}

Javascript map method on array of string elements

I am trying to understand how to implement the map method (rather than using a for loop) to check a string for palindromes and return boolean values for whether the mapped array elements reversed are the same as the original array elements. I cannot seem to understand the syntax of the map method. How do I get the map to function on each element in the original array? What is the value? Here is my working code, which is only logging a value of undefined:
function palindromeChecker(string) {
var myString = string.toLowerCase();
var myArray = myString.split(" ");
var newArray = myArray.map(function (item) {
item.split("").reverse().join("");
return newArray === myArray;
});
}
console.log(palindromeChecker("What pop did dad Drink today"));
Here is a link to the fiddle:
https://jsfiddle.net/minditorrey/3s6uqxrh/1/
There is one related question here:
Javascript array map method callback parameters
but it doesn't answer my confusion about the syntax of the map method when using it to perform a function on an array of strings.
The map method will literally 'map' a function call onto each element in the array, take this as a simple example of increasing the value of each integer in an array by 1:
var items = [1,2,3];
items.map(function(item) {
return item + 1;
});
// returns [2,3,4]
In your case, you are trying to use map to accept or reject a string if it's a palindrome, so a simple implementation might be:
var items = ['mum', 'dad', 'brother'];
items.map(function(item) {
return item.split('').reverse().join('') === item;
});
// returns [true, true, false]
I'm not 100% sure of your reasons for using map, because if you were trying to just filter the array and remove the strings that aren't palindromes, you should probably use the filter method instead, which works in the same way, but would remove any that return false:
var items = ['mum', 'dad', 'brother'];
items.filter(function(item) {
return item.split('').reverse().join('') === item;
});
// returns ['mum', dad']
In your case you are splitting a string first to get your array of characters; you may also want to make that string lower case and remove punctuation, so an implementation might be:
var string = 'I live at home with my Mum, my Dad and my Brother!';
var items = string.toLowerCase().replace(/[^a-z0-9-\s]+/, '').split(' ');
items.filter(function(item) {
return item.split('').reverse().join('') === item;
});
// returns ['i', 'mum', dad']
As mentioned in one of the comments on your question, you need to ensure you return a value from your function if you are using a separate function to perform the check, so this is how your function should look:
function checkPalindromes(string) {
var items = string.toLowerCase().replace(/[^a-z0-9-\s]+/, '').split(' ');
items.filter(function(item) {
return item.split('').reverse().join('') === item;
});
return items;
}
And you would call it using:
checkPalindromes('I live at home with my Mum, my Dad and my Brother!'); // ['i', 'mum', 'dad']
try something like this:
let str = 'hello';
let tab = [...str];
tab.map((x)=> {
console.log("|"+x+"|");
return x;
})
newArray should include reversed version of theall items in myArray. After that, newArray should be reversed and joined with space in order to get the reversed version of the input string.
Here is the code:
function palindromeChecker(string) {
var myString = string.toLowerCase();
var myArray = myString.split(" ");
var newArray = myArray.map(function (item) {
return item.split("").reverse().join("");
});
console.log(newArray);
return newArray.reverse().join(" ") === string;
}
console.log(palindromeChecker("dad did what"));
Javascript map method on array of string elements by using split() function.
let str = 'hello';
str.split('').map((x)=> {
console.log("|"+x+"|");
return x;
})
Map is a higher-order function available in ES5. I think your newArraywill contain an array of boolean values.
In essence, map will iterate over every value in your array and apply the function. The return value will be the new value in the array. You can also use map and save the information you need somewhere else, and ignore the result of course.
var arr = [1,2,3,4];
var newArray = arr.map(function(i) {
return i * 2;
});
//newArray = [2,4,6,8]
The map function in javascript (and pretty much in any language) is a great little function that allows you to call a function on each of the items on a list, and thus changing the list itself.
The (anonymous) function you're passing as an argument accepts an argument itself, which is filled by an item of the list it is working on, each time it is called.
So for a list [1,2,3,4], the function
function(item) { return item + 1 }, would give you a list of [2,3,4,5] for a result. The function you passed to $.map() is run over each element of the list, and thus changing the list.
So for your code: in the function you're passing as an argument to $.map(), you're returning whether the old and new array are equal (which is false btw). So since you're returning a boolean value, the list you'll end up with is a list of bools.
What I think you want to do, is extract the newArray == myArray from the function you're passing to $.map(), and putting it after your $.map() call.
Then inside the function you're passing to $.map(), return the item you're splitting and whatnot, so your newArray will be an array of strings like myArray.
Apart from a few minor mistakes in your code, such as scope issues (you're referencing the "newArray" and "myArray" outside of the function in which they where defined, and therefore, getting "undefined")..
The main issue you had is that you addressed the ENTIRE array inside the map function, while the whole concept is breaking things down to single elements (and then the function collects everything back to an array for you).
I've used the "filter" function in my example, because it works in a similar manner and I felt that it does what you wanted, but you can change the "filter" to a "map" and see what happends.
Cheers :)
HTML:
<body>
<p id="bla">
BLA
</p>
<p id="bla2">
BLA2
</p>
</body>
Javascript:
function palindromeChecker(string) {
var myString = string.toLowerCase();
var myArray = myString.split(" ");
var newArray = myArray.filter(function (item) {
var reversedItem = item.split('').reverse().join('');
return item == reversedItem;
});
document.getElementById("bla").innerHTML = myArray;
document.getElementById("bla2").innerHTML = newArray;
}
palindromeChecker("What pop did dad Drink today");
Thanks for your input, all. This is the code I ended up with. I fixed the scope issues in the original post. My main problem was understanding the syntax of the map method. In particular, I could not understand from other online resources how to determine the value in the callback function. So, with much help from above I have placed the map method inside the palindromeChecker, and done all of the work on the array inside the map function.
var palindromeChecker = function(string) {
var newString = string.toLowerCase().split(' ');
newString.map(function(item) {
console.log(item.split('').reverse().join('') === item);
});
};
palindromeChecker("What pop did dad drink today");
//Returns false, true, true, true, false, false

Get the difference between two arrays of objects

I've got two arrays of objects, the difference between them is only that arrayAfter will have an element added:
var arrayBefore = [
{"name":"Alan","height":"171","weight":"66"},
{"name":"Ben","height":"182","weight":"90"}
];
var arrayAfter= [
{"name":"Alan","height":"171","weight":"66"},
{"name":"Ben","height":"182","weight":"90"},
{"name":"Chris","height":"163","weight":"71"}
];
"name" is always unique!
How can I find out which one is the element that has been added? I've tried ending up using nested for loops, but this seems overcomplicated.
I've also found the this nice idea:
var diff = $(arrayAfter).not(arrayBefore ).get();
However, that does not seem to work on arrays of objects straight ahead.
Is there some easy way to get the difference?
If only the name indicates uniqueness, you can do:
//Get a list of all the names in the before array
var beforeNames = arrayBefore.map(function(person) { return person.name });
//Filter the after array to only contain names not contained in the before array
var uniqueObjects = arrayAfter.filter(function(person) {
return beforeNames.indexOf(person.name) === -1;
});
console.log(uniqueObjects); //[{"name":"Chris","height":"163","weight":"71"}]
Demo: http://jsfiddle.net/tehgc8L5/
For a generic method you can combine Array.prototype.filter() with Array.prototype.reduce() which iterates over the object keys:
arrayAfter.filter(function(after) {
return !arrayBefore.reduce(function(found, before) {
if (!found) {
found = true;
for (key in before) {
if (before.hasOwnProperty(key)) {
found = found && (before[key] === after[key]);
}
}
}
return found;
}, false);
}); //[{name: "Chris", height: "163", weight: "71"}]
You can use Array.prototype.filter and filter out those elements in the previous array.
var differences = arrayAfter.filter(function(el) {
return arrayBefore.indexOf(el) === -1;
});
I believe jQuery will have nothing that will directly solve your problem here. Your problem being comparing objects for equality.
I am assuming that name is unique. If not, for this method you will need a unique identifier for data. If you absolute do not have one then you could concat all data to get one.
// first make a map of objects in before
var before = {};
arrayBefore.forEach(function(o){
before[o.name] = o;
});
// now we get the elements of after that do not exist in our hashmap
var result = arrayAfter.filter(function(o){
return !(o.name in before);
});
You can obviously wrap this up in a general function.

Removing items from array in AngularJS

I have this two integers arrays:
I am working on my Angularjs tutorial project.
In controller I have this two arrays:
var arrA=[12,54,76,98,45];
var arrB=[12,98];
I need to delete from arrA all numbers that inside arrB.
arrA have to be like this after implementation:
arrA=[54,76,45]
What is best and elegantic way to implement it in angularjs?
You can use Array.prototype.filter() in conjunction with Array.prototype.indexOf()
The filter() method creates a new array with all elements that pass the test implemented by the provided function.
The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.
var arrA=[12,54,76,98,45];
var arrB=[12,98];
arrA = arrA.filter(function(o){
return arrB.indexOf(o) == -1;
});
document.write(JSON.stringify(arrA));
Off the top of my head.
//Run a loop to go through all elements in arrB
for (var i=0;i<arrB.length;i++) {
//keep position of element i in arrA
//if it's not there index will be equal to -1
var index=arrA.indexOf(arrB[i])
//if it is there
if(index!=-1) {
//remove 1 element at position index from arrA
arrA.splice(index,1)
}
}
Good luck.
This has nothing to do with angular btw, it's basic javascript.
Here's a fiddle:
https://jsfiddle.net/MichaelSel/t2dfg31c/
how about the following:
var result = arrA.filter(function(elem){
return arrB.indexOf(elem) === -1;
);
To delete items from any array you need to use splice:
$scope.items.splice(index, 1);
now what you can do is, you can run a for loop to identify the duplicate element. Once identified you can remove it using splice function.
Angular doesn't concern itself with things like array manipulation. JavaScript provides facilities for that though:
var diff = arrA.filter(function(item) {
return arrB.indexOf(item) < 0;
});
Fiddle
If arrB is very large, you might want to allow it to be O(N) (for smallish ones) up to O(N log N), instead of O(n^2):
var lookup = arrB.reduce(function(lookup, item) {
lookup[item] = true;
return lookup;
}, {});
diff = arrA.filter(function(item) {
return !Object.prototype.hasOwnProperty.call(lookup, item);
});
However, this only works if the string representation of the item is what you are looking at. It would work for integers.

Categories

Resources