How to find whether an array has other element or not? - javascript

I have any array
var myArr = [1,1,1,1,1];
if all the elements in an array are same, then we return true and else false.
eg : myArr[1,1,1,1,1] return true;
myArr[1,2,1,1,1] return false;
for(var i=0; i<myArr.length; i++){
if(myArr[i] != myArr[i+1]){
flg = false;
}
}
Can anyone help me to design this code.

That's why .every is there
var myArr = [1,1,1,1,2 ];
var myArr2 = [1,1,1,1,1,2,3,4,5];
console.log(myArr.every(o=> myArr2.indexOf(o) >=0 ))

Create a function and return false if any element of a array is not equal to 1 .
function retStat( myArr ){
for(var i=0; i<myArr.length; i++){
if(myArr[i] != 1){
return false;
}
}
return true;
}
arr1 = [1,1,1,1,1];
arr2 = [1,2,1,1,1];
console.log( retStat( arr1 ) ); // true
console.log( retStat( arr2 ) ); // false

This can also be achieved without loop. You can check for the first element to the entire string represenattion of the array. If the match is found for all characters in the string it will give you blank value as ''. Using this you can know if the array has all same elements or there is different elements present there.
function isSame(arr){
var str = arr.join('');
var re = new RegExp(arr[0],"g");
var replacedStr = str.replace(re,'');
return !Boolean(replacedStr);
}
var myArr = [1,1,1,1,1];
console.log(isSame(myArr));
myArr = [1,2,1,1,1];
console.log(isSame(myArr));
myArr = [1,1,1,5,1];
console.log(isSame(myArr));

Since you want to check whether all elements in array are the same you can compare all of them to first element.
Function some returns as its callback returns true, so callback isn't called after first mismatch is found.
console.log(check([1,1,1]));
console.log(check([1,2,3]));
console.log(check([]));
function check(arr){
if (!arr.length){
return false;
}
return !arr.some(el=> el !== arr[0]);
}

I think this works:
<script type="text/javascript">
var myArr = [1,1,1,1,1];
flg=true;
for(var i=0; i<myArr.length; i++)
{
if(i==(myArr.length-1))
{
if(myArr[i]!=myArr[i-1])
{
flg=false;
}
}
else
{
if(myArr[i] != myArr[i+1])
{
flg=false;
return false;
}
}
}
console.log(flg);
</script>

Small mistake, you are checking for next element myArr[i+1] which is undefined at last loop
Check with condition myArr.length-1
for(var i=0; i<myArr.length-1; i++){
if(myArr[i] != myArr[i+1]){
flg = false;
break;
}
}

Here is a solution inspired by this answer https://stackoverflow.com/a/9229821/5061000
What does the below function in snippet do?
Removes all the duplicate items,
Returns true if .length == 1 (i.e. all values are the same!).
function array_all_same(a) {
return a.filter(function(item, pos) {
return a.indexOf(item) == pos;
}).length == 1;
}
var myArr1 = [1, 1, 1, 1, 1];
console.log(array_all_same(myArr1));
var myArr2 = [1, 2, 1, 1, 1];
console.log(array_all_same(myArr2));
Hope it helps!

Related

Create a function to evaluate if all elements in the array are the same

Problem
I'm trying to create a function that evaluates an array and if every element inside the array is the same, it would return true and otherwise false. I don't want it to return true/false for each individual element, just for the entire array.
Attempt 1
This method works, but it returns true/false for each element in the array:
function isUniform(arr){
let first = arr[0];
for (let i = 1; i <arr.length; i++){
if (arr[0] !== arr[i]){
console.log(false);
} else {
console.log(true);
}
}
}
Attempt 2
This method returns true/false, once and then prints true again at the end:
function isUniform(arr){
let first = arr[0];
for (let i = 1; i <arr.length; i++){
if (arr[0] !== arr[i]){
console.log(false);
}
}
console.log(true);
}
If you want to test if something is true for every element of an array, you don't really need to write much — you can use array.every for this and just compare the first element. every() is nice because it will return early if a false condition is found.
var arr1 = [1, 1, 1, 1, 1, 1, 1]
var arr2 = [1, 1, 1, 2, 1, 1, 1]
console.log(arr1.every((n, _, self) => n === self[0]))
console.log(arr2.every((n, _, self) => n === self[0]))
This will return true for an empty array, which may or may not be what you want.
Alternative using the object Set
new Set(arr).size === 1 // This means all the elements are equal.
let isUniform = (arr) => new Set(arr).size === 1;
console.log(isUniform([4,4,4,4,4]));
console.log(isUniform([4,4,4,4,4,5]));
Add a return statement with false and end the function. The return value could be used later.
function isUniform(arr) {
let first = arr[0];
for (let i = 1; i < arr.length; i++) {
if (arr[0] !== arr[i]) {
console.log(false);
return false;
}
}
console.log(true);
return true;
}
For using a return value, you need to return true at the end, too.
Try with Array#every .its Checking all other value is same with first index of array
function isUniform(arr) {
return arr.every(a=> a === arr[0])
}
console.log(isUniform([2,2,2,2]));
console.log(isUniform([4,4,4,4,4,5]));
The problem is that you need to stop once you've found the first false element:
function isUniform(arr){
let first = arr[0];
let uniform = true;
for (let i = 1; i <arr.length; i++){
if (arr[0] !== arr[i]){
uniform = false;
break;
}
}
console.log(uniform);
}

javascript check values are same or not within double quotes?

In javascript if any variable has multiple values seperated by comma within double quotes,then how to check that values are same or not
var str= "0,1,-1";
How to check this variable.
The author wants to compare these 3 values. You most separate this variable with split:
var str= "0,1,-1",
arr = str.split(',');
all are same or not ie, true are false compare this array with function every
var str= "0,1,-1",
arr = str.split(',');
var res = arr.every(function (item) {
return item == arr[0];
})
console.log(res);
Short solution using String.prototype.split() and Set object:
var hasSameValues = function (s) {
return (new Set(s.split(','))).size === 1;
};
console.log(hasSameValues("0,1,-1"));
console.log(hasSameValues("1,1,1"));
console.log(hasSameValues("2,-2,2"));
you can split and then check for every item in splitted array.
check the fiddle
code is below -
var val = "1, 01, 0001";
var result = function(val)
{
var l = val.length;
if(l == 0)
{
return false;
}
else
{
//because all the values in 'val' fields are number
var f = Number.parseInt(val[0]) ;
for(i=1; i< l; i++)
{
if(Number.parseInt(val[i]) != f)
{
return false;
}
}
return true;
}
}(val.split(','))
alert(result);

Array.prototype.indexOf() cannot find array inside of multi-dimensional array [duplicate]

Let's say we have the following js array
var ar = [
[2,6,89,45],
[3,566,23,79],
[434,677,9,23]
];
var val = [3,566,23,79];
Is there a js builtin function or jQuery one with which you can search the array ar for val?
Thanks
***UPDATE*************
Taking fusion's response I created this prototype
Array.prototype.containsArray = function(val) {
var hash = {};
for(var i=0; i<this.length; i++) {
hash[this[i]] = i;
}
return hash.hasOwnProperty(val);
}
you could create a hash.
var ar = [
[2,6,89,45],
[3,566,23,79],
[434,677,9,23]
];
var hash = {};
for(var i = 0 ; i < ar.length; i += 1) {
hash[ar[i]] = i;
}
var val = [434,677,9,23];
if(hash.hasOwnProperty(val)) {
document.write(hash[val]);
}
You can also use a trick with JSON serializing. It is short and simple, but kind of hacky.
It works, because "[0,1]" === "[0,1]".
Here is the working demo snippet:
Array.prototype.indexOfForArrays = function(search)
{
var searchJson = JSON.stringify(search); // "[3,566,23,79]"
var arrJson = this.map(JSON.stringify); // ["[2,6,89,45]", "[3,566,23,79]", "[434,677,9,23]"]
return arrJson.indexOf(searchJson);
};
var arr = [
[2,6,89,45],
[3,566,23,79],
[434,677,9,23]
];
document.body.innerText = arr.indexOfForArrays([3,566,23,79]);
function indexOfArray(val, array) {
var hash = {};
for (var i = 0; i < array.length; i++) {
hash[array[i]] = i;
}
return (hash.hasOwnProperty(val)) ? hash[val] : -1;
};
I consider this more useful for than containsArray(). It solves the same problem (using a hash table) but returns the index (rather than only boolean true/false).
Can you try this?
var ar = [
[2,6,89,45],
[3,566,23,79],
[434,677,9,23]
];
var val = [3,566,23,79];
var sval = val.join("");
for(var i in ar)
{
var sar = ar[i].join("");
if (sar==sval)
{
alert("found!");
break;
}
}
Why don't you use javascript array functions?
function filterArrayByValues(array, values) {
return array.filter(function (arrayItem) {
return values.some(function (value) {
return value === arrayItem;
});
});
}
Or if your array is more complicated, and you want compare only one property but as result return whole object:
function filterArrayByValues(array, values, propertyName) {
return array.filter(function (arrayItem) {
return values.some(function (value) {
return value === arrayItem[propertyName];
});
});
}
More about used functions: filter() and some()
You can use Array.prototype.some(), Array.prototype.every() to check each element of each array.
var ar = [
[2, 6, 89, 45],
[3, 566, 23, 79],
[434, 677, 9, 23]
];
var val = [3, 566, 23, 79];
var bool = ar.some(function(arr) {
return arr.every(function(prop, index) {
return val[index] === prop
})
});
console.log(bool);
I guess there is no such JS functionality available. but you can create one
function arrEquals( one, two )
{
if( one.length != two.length )
{
return false;
}
for( i = 0; i < one.length; i++ )
{
if( one[i] != two[i] )
{
return false;
}
}
return true;
}
The problem with this is that of object/array equality in Javascript. Essentially, the problem is that two arrays are not equal, even if they have the same values. You need to loop through the array and compare the members to your search key (val), but you'll need a way of accurately comparing arrays.
The easiest way round this is to use a library that allows array/object comparison. underscore.js has a very attractive method to do this:
for (var i = 0; i < ar.length; i++) {
if (_.isEqual(ar[i], val)) {
// value is present
}
}
If you don't want to use another library (though I would urge you to -- or at least borrow the message from the Underscore source), you could do this with JSON.stringify...
var valJSON = JSON.stringify(val);
for (var i = 0; i < ar.length; i++) {
if (valJSON === JSON.stringify(ar[i]) {
// value is present
}
}
This will almost certainly be significantly slower, however.
You can use toString convertion to compare elements
var ar = [
[2,6,89,45],
[3,566,23,79],
[434,677,9,23]
];
var val = [3,566,23,79];
s = !ar.every(a => (a.toString() != val.toString()));
console.log(s) // true
Use this instead
if (ar.join(".").indexOf(val) > -1) {
return true;
} else {
return false;
}
Use lodash isEqual
const isValIncludedInAr = ar.some(element => isEqual(element, val))
const arrayOne = [2,6,89,45];
const arrayTwo = [3,566,23,79];
const arrayThree = [434,677,9,23];
const data = new Set([arrayOne, arrayTwo, arrayThree]);
// Check array if exist
console.log( data.has(arrayTwo) ); // It will return true.
// If you want to make a set into array it's simple
const arrayData = [...data];
console.log(arrayData); // It will return [[2,6,89,45], [3,566,23,79], [434,677,9,23]]

How do I know an array contains all zero(0) in Javascript

I have an array. I need to generate an alert if all the array items are 0.
For example,
if myArray = [0,0,0,0];
then alert('all zero');
else
alert('all are not zero');
Thanks.
You can use either Array.prototype.every or Array.prototype.some.
Array.prototype.every
With every, you are going to check every array position and check it to be zero:
const arr = [0,0,0,0];
const isAllZero = arr.every(item => item === 0);
This has the advantage of being very clear and easy to understand, but it needs to iterate over the whole array to return the result.
Array.prototype.some
If, instead, we inverse the question, and we ask "does this array contain anything different than zero?" then we can use some:
const arr = [0,0,0,0];
const someIsNotZero = arr.some(item => item !== 0);
const isAllZero = !someIsNotZero; // <= this is your result
This has the advantage of not needing to check the whole array, since, as soon it finds a non-zero value, it will instantly return the result.
for loop
If you don't have access to modern JavaScript, you can use a for loop:
var isAllZero = true;
for(i = 0; i < myArray.length; ++i) {
if(myArray[i] !== 0) {
isAllZero = false;
break;
}
}
// `isAllZero` contains your result
RegExp
If you want a non-loop solution, based on the not-working one of #epascarello:
var arr = [0,0,0,"",0],
arrj = arr.join('');
if((/[^0]/).exec(arrj) || arr.length != arrj.length){
alert('all are not zero');
} else {
alert('all zero');
}
This will return "all zero" if the array contains only 0
Using ECMA5 every
function zeroTest(element) {
return element === 0;
}
var array = [0, 0, 0, 0];
var allZeros = array.every(zeroTest);
console.log(allZeros);
array = [0, 0, 0, 1];
allZeros = array.every(zeroTest);
console.log(allZeros);
Use an early return instead of 2, 3 jumps. This will reduce the complexity. Also we can avoid initialisation of a temp variable.
function ifAnyNonZero (array) {
for(var i = 0; i < array.length; ++i) {
if(array[i] !== 0) {
return true;
}
}
return false;
}
Using Math.max when you know for certain that no negative values will be present in the array:
const zeros = [0, 0, 0, 0];
Math.max(...zeros) === 0; // true
No need to loop, simple join and reg expression will work.
var arr = [0,0,0,10,0];
if((/[^0]/).exec(arr.join(""))){
console.log("non zero");
} else {
console.log("I am full of zeros!");
}
Another slow way of doing it, but just for fun.
var arr = [0,0,0,0,10,0,0];
var temp = arr.slice(0).sort();
var isAllZeros = temp[0]===0 && temp[temp.length-1]===0;
you can give a try to this :
var arr = [0,0,0,0,0];
arr = arr.filter(function(n) {return n;});
if(arr.length>0) console.log('Non Zero');
else console.log("All Zero");

Check if each item in an array is identical in JavaScript

I need to test whether each item in an array is identical to each other. For example:
var list = ["l","r","b"]
Should evaluate as false, because each item is not identical. On the other hand this:
var list = ["b", "b", "b"]
Should evaluate as true because they are all identical. What would be the most efficient (in speed/resources) way of achieving this?
In ES5, you could do:
arr.every(function(v, i, a) {
// first item: nothing to compare with (and, single element arrays should return true)
// otherwise: compare current value to previous value
return i === 0 || v === a[i - 1];
});
.every does short-circuit as well.
function identical(array) {
for(var i = 0; i < array.length - 1; i++) {
if(array[i] !== array[i+1]) {
return false;
}
}
return true;
}
You could always do a new Set, and check the length.
var set1 = [...new Set(list)].length === 1;
The one line answer is:
arr.every((val, ind, arr) => val === arr[0]);
You can look into Array.every for more details.
Note:
Array.every is available ES5 onwards.
This method returns true for any condition put on an empty array.
Syntax: arr.every(callback[, thisArg]) or array.every(function(currentValue, index, arr), thisValue)
It does not change the original array
The execution of every() is short-circuited. As soon as every() finds an array element that doesn't match the predicate, it immediately returns false and doesn't iterate over the remaining elements
arr.every(i=>i==arr[0]) //will return true if all items in arr are identical
function matchList(list) {
var listItem = list[0];
for (index in list) {
if(list[index] != listItem {
return false;
}
}
return true;
}
var list = ["b", "b", "b"];
var checkItem = list[0];
var isSame = true;
for (var i = 0; i < list.length; i++) {
if (list[i] != checkItem) {
isSame = false;
break;
}
}
return isSame;
function identical(array) {
// a variable holding standard value
//against this standard value we are examining the array
var standard = array[1];
for (var i = 0; i < array.length; i++) {
if (array[i] !== standard) {
return false;
}
}
return true;
}
identical([1, 1, 1, 1, 1]); //return true
identical(['a', 'a', 'a']); //return true
identical(['a', 'a', 'b'])
function identical(array) {
// a variable holding standard value
//against this standard value we are examining the array
var standard = array[1];
for (var i = 0; i < array.length; i++) {
if (array[i] !== standard) {
return false;
}
}
return true;
}
identical([1, 1, 1, 1, 1]); //return true
identical(['a', 'a', 'a']); //return true
identical(['a', 'a', 'b'])
My suggestion would be to remove duplicates (check out Easiest way to find duplicate values in a JavaScript array), and then check to see if the length == 1. That would mean that all items were the same.
function allEqual(list)
{
if(list.length == 0 || list.length == 1)
{
return true;
}
for (index in list) {
if(list[index] != list[index+1] {
return false;
}
}
return true;
}

Categories

Resources