Does jQuery have a method for checking all values of an array to see if they meet some criteria? - javascript

I'm looking for something similar to Groovy's every() method, which tests every element of a list if it meets some criteria. If they all meet the criteria, the function returns true. Otherwise, false. I've tried something like this:
var arr = [1, 0, 1, 0, 1, 1];
var allOnes = $.grep(arr, function(ind) {
return this == 1;
}).length == arr.length;
..but its not very clean. I haven't had any luck while searching through the API. Is using grep() the only way to do it?

if it is a plain js array, you have $.grep()
.filter() is for use with jQuery or DOM Elements

Here is a plugin I made that might make it easier:
(function($) {
$.fn.allOnes = function() {
var allVal = true;
this.each(function(ind, item) {
if (item != 1) {
allVal = false;
return allVal;
}
});
return allVal;
};
})(jQuery);
var arr = [1, 1, 0, 1, 1, 1];
console.log($(arr).allOnes());
Fiddle: http://jsfiddle.net/maniator/NctND/
The following plugin is an expansion of the above and lets you search for a specific number: http://jsfiddle.net/maniator/bFNnn/
(function($) {
$.fn.allValue = function(pred) {
var allOnes = true;
this.each(function(ind, item) {
if (item != pred) {
allOnes = false;
return allOnes;
}
});
return allOnes;
};
})(jQuery);
var arr = [1, 1, 1, 1, 1, 1];
console.log($(arr).allValue(1));

here is example of function you can use.
var arr = [1, 0, 1, 0, 1, 1];
var allOnes = arr.check(1);
//this function compares all elements in array and if all meet the criteria it returns true
Array.prototype.chack = function(cond)
{
var ln = 0;
for(i=0; i<this.length; i++)
{
if(bond === this[i])
{
ln++
}
}
if(ln == this.length)
return true;
else
return false;
}

How about just turning your working code into a method on array, to ease its reuse:
Array.prototype.every = function(predicate){
return $.grep(this,predicate).length == this.length;
}
usage:
alert([1,0,1,0].every(function(i) { return i == 1; }));
Working example: http://jsfiddle.net/59J5A/
Edit: changed to grep

You could always implement an allOnes method:
function allOnes(array) {
var result = [];
for(var i = 0; i < array.length; i += 1) {
if (array[i] === 1) { result.push(true); }
}
return array.length == result.length;
}
or you could be a bit more abstract and test for true/false:
function all(array) {
var result = [];
for(var i = 0; i < array.length; i += 1) {
if (array[i]) { result.push(true); }
}
return array.length == result.length;
}
var arr = [1, 0, 1, 0, 1, 1];
var allOnes = all(arr);
or even better, maybe have a changeable predicate:
function all(array, predicate) {
var result = [],
predicate = predicate || function(x) { if (x) { return true; } };
for(var i = 0; i < array.length; i += 1) {
if (predicate(array[i])) { result.push(true); }
}
return array.length == result.length;
}
var allOnes = all(arr, function(x) { return x === 1; })

Related

removing duplicate numbers out of both arrays

I know that you can remove 1 of the duplicate number out of an array but is there a way you can remove the number if they're duplicate? So far, below code is what I have. I wanted to use for loop to remove the number out of the array if they're equal, but I dont think I coded it correctly or it's not complete. I want it to return [3, 4, 5]
function sym(args) {
var array = [];
var join;
for(var i = 0; i < arguments.length; i++){
array.push(arguments[i]);
join = array[0].concat(array[1]);
}
join.sort();
for(var j = 0; j < join.length; j++) {
if(join[j] === join[j+1]) {
var removed = join.splice(j, join[j+2]);
console.log(removed);
}
}
return join;
}
sym([1, 2, 3], [5, 2, 1, 4]);
Here's my take
function sym() {
var vals = {};
var rarray= [];
var a=arguments;
for (var i=0,l=a.length;i<l;i++) {
if (a[i] instanceof Array) {
for (var n=0,ln=a[i].length;n<ln;n++) {
vals[a[i][n]]=vals[a[i][n]]||[];
vals[a[i][n]].push(a[i][n]);
}
}
}
for (var i in vals) {
if (vals.hasOwnProperty(i)) {
if (vals[i].length===1)
rarray.push(i);
}
}
return rarray;
}
Examples:
sym([1, 2, 3], [5, 2, 1, 4]);
// return: ["3", "4", "5"]
sym([1, 2, 3], [5, 2, 1, 4],[4,6,7,8],[8,4]);
// ["3", "5", "6", "7"]
sym([1,2],[1]);
// return: ["2"]
var sym = function (ar1, ar2) {
return ar1
.concat(ar2)
.sort(function (a, b) { return a - b; })
.filter(function (elem, i, ar) {
return ar[i-1] !== elem && ar[i+1] !== elem;
});
}
I like Crayon Violent's solution, but I don't see the point in maintaining arrays of duplicate items when you can simply count them.
This provides a large performance increase (jsperf), while also simplifying the code.
function sym() {
var occurrences = {};
var inputArrays = arguments;
var uniqueItems = [];
function addOccurrences(arr) {
for (var i = 0, len=arr.length; i < len; i++) {
occurrences[arr[i]] = 1 + (occurrences[arr[i]] || 0);
}
}
for (var i=0, len=inputArrays.length; i < len; i++) {
if (inputArrays[i] instanceof Array) {
addOccurrences(inputArrays[i]);
}
}
for (var item in occurrences) {
if (occurrences[item] === 1) {
uniqueItems.push(item);
}
}
return uniqueItems;
}
Which can be made nicer if you happen to have underscore or lodash in your project:
function sym() {
var inputArrays = _.filter(arguments, _.isArray);
var occurrences = {};
function addOccurrences(arr) {
_.forEach(arr, function(item){
occurrences[item] = 1 + (occurrences[item] || 0);
});
}
_.forEach(inputArrays, addOccurrences);
// Select the items with one occurence, return the keys (items)
return _.filter(_.keys(occurrences), function(item){
return occurrences[item] === 1;
});
}

Array Pattern using Javascript

I have an array: Myarray=[1,0,0,1,0,1,1,0,0]
I want to display the elements of the array in the pattern 1,0,1,0..
I tried to set a flag:
for (var i = 0; i < myArray.length; i++) {
if (myArray[i] == flag) {
newArray = newArray + myArray[i];
if (flag == 0)
flag = 1;
else
flag = 0;
}
But the problem is the mismatched elements are not showing in output.
Any Idea? Thanks.
Generating a new Array of 1, 0, 1, 0, ... with length equal to myArray.length can be done in one line with Array.prototype.map
var newArr = myArray.map(function (e, i) {return 1 - (i % 2);});
However, it may be more efficient to use a loop;
var newArr = [],
i = myArray.length;
while (i-- > 0)
newArr[i] = 1 - (i % 2);
newArr; // [1, 0, 1, 0, 1, 0, 1, 0, 1]
If you want to filter out consecutive repeating items, you can use Array.prototype.filter with a variable outside the filter function to remember what you last saw
var newArray = (function () {
var last;
return myArray.filter(function (e) {
var t = last;
last = e;
if (t === last)
return false;
return true;
});
}());
Or again in a loop
var newArr = [],
last,
i;
for (i = 0; i < myArray.length; ++i)
if (last !== myArray[i]) {
last = myArray[i];
newArr.push(last);
}
newArr; // [1, 0, 1, 0, 1, 0]
Just initialize newArray to the first element of your Array then enter the for-loop checking if the next value is not equal to the last element of new array. Your code will look something like:
newArray[0]=myArray[0];
for (var i = 1; i < myArray.length; i++) {
if(newArray[i-1]!=myArray[i]) {
newArray.push(myArray[i]);
}
}
Pulling only elements that match a pattern:
var a = [1,0,0,1,0,1,1,0,0],
pat = [1,0,1,0,1,0,1,0,1],
matched = a.map(function(a1, idx) { return a[idx] === pat[idx] ? a1 : null } );
console.log(matched); // [1, 0, null, null, null, null, 1, 0, null]

How can I use a Function to determine if a Value exists in a Javascript Array?

I will be using an input field where a person types in a value.
I create the variable that they will type in: 'Ben'.
I want the function to loop thru the nameArray and return true or false.
The script is not working and I know it is rather simple.
function validateNames() {
var name = "Ben";
var nameArray = ["Bill", "Barry", "Zack", "Will"];
var arrayLength = nameArray.length;
for (var i = 0; i < arrayLength; i++) {
//Do something
if (name != nameArray[i]) {
alert((nameArray[i]) + "Name is not valid.");
console.log("Name is not found in array.");
} else {
return true;
console.log(nameArray[i]);
}
}
}
The only way for your loop logic to know that the value is not in the array is to go through the whole array first. Your loop will be alerting on every iteration until it finds a match. It also doesn't make sense to put a console.log after a return because the former will never execute:
function validateNames() {
var name = "Ben";
var nameArray = ["Bill", "Barry", "Zack", "Will"];
var arrayLength = nameArray.length;
for (var i = 0; i < arrayLength; i++) {
if (name === nameArray[i]) {
console.log(nameArray[i]);
return true;
}
}
console.log("Name is not found in array.");
return false;
}
validateNames();
Javascript arrays also provide a handy method for checking whether they contain a certain value. it's called .indexOf(), and it returns -1 when there's no match:
function validateNames() {
var name = "Ben";
var nameArray = ["Bill","Barry","Zack","Will"];
return nameArray.indexOf(name) !== -1;
}
You could use .indexOf():
var nameArray = ["Bill","Barry","Zack","Will"];
nameArray.indexOf("Bill"); // Returns 0, Bill is found
nameArray.indexOf("Hillary"); // Returns -1, Hillary not found
So your function could look like:
function validateName(name) {
return nameArray.indexOf(name) !== -1;
}
Please bear in mind it does not work on IE8 or below.
easy fix :)
var nameArray = ["Bill", "Barry", "Zack", "Will"];
console.log(validateName("Ben", nameArrray)); // False
console.log(validateName("Will", nameArrray)); // True
function validateName(name, arr){
var found = 0;
for(var i = 0; i < arr.length; i++){
found += (name === arr[i])? 1 : 0;
}
var result = (found>0)? true: false;
return result;
}
This will be false, because Ben does not exist in the array
if (nameArray.indexOf(name) > -1)
You can add a contains() method to the Array class so that you do not have to type this out each time.
// Static method
if (Array.contains === undefined) {
Array.contains = function(arr, val) {
return arr.indexOf(val) > -1;
}
}
// Instance method
if (Array.prototype.contains === undefined) {
Array.prototype.contains = function(val) {
return this.indexOf(val) > -1;
}
}
var nameArray = ["Bill", "Barry", "Zack", "Will"];
var name = "Ben";
Array.contains(nameArray, name); // false
nameArray.contains(name); // false
You could also use some Array.prototype.some.
if (Array.prototype.contains === undefined) {
Array.prototype.contains = function(val) {
return this.some(function(item) {
return item === name;
});
}
}
A better approach is to polyfill Array.prototype.includes(). This is an upcoming method in ECMAScript 7.
Polyfill
if (![].includes) {
Array.prototype.includes = function(searchElement /*, fromIndex*/ ) {'use strict';
var O = Object(this);
var len = parseInt(O.length) || 0;
if (len === 0) {
return false;
}
var n = parseInt(arguments[1]) || 0;
var k;
if (n >= 0) {
k = n;
} else {
k = len + n;
if (k < 0) {k = 0;}
}
var currentElement;
while (k < len) {
currentElement = O[k];
if (searchElement === currentElement ||
(searchElement !== searchElement && currentElement !== currentElement)) {
return true;
}
k++;
}
return false;
};
}
Usage
[1, 2, 3].includes(2); // true
[1, 2, 3].includes(4); // false
[1, 2, 3].includes(3, 3); // false
[1, 2, 3].includes(3, -1); // true
[1, 2, NaN].includes(NaN); // true

Remove duplicate item from array Javascript [duplicate]

This question already has answers here:
Get all non-unique values (i.e.: duplicate/more than one occurrence) in an array
(97 answers)
Closed 8 years ago.
I'm looking for an easy way of removing a duplicate value from an array. I figured out how to detect if there is a duplicate or not, just I don't know how to "push" it from the value. For example, if you go to the link provided, and then type, "abca" (press return/enter key after each letter).. it will alert "duplicate!"
But I also want to figure out how to remove that duplicate from the textarea?
http://jsfiddle.net/P3gpp/
This is the part that seems to not be working ::
sort = sort.push(i);
textVal = sort;
return textVal;
Why do it the hard way, it can be done more easily using javascript filter function which is specifically for this kind of operations:
var arr = ["apple", "bannana", "orange", "apple", "orange"];
arr = arr.filter( function( item, index, inputArray ) {
return inputArray.indexOf(item) == index;
});
---------------------
Output: ["apple", "bannana", "orange"]
Based on user2668376 solution, this will return a new array without duplicates.
Array.prototype.removeDuplicates = function () {
return this.filter(function (item, index, self) {
return self.indexOf(item) == index;
});
};
After that you can do:
[1, 3, 3, 7].removeDuplicates();
Result will be; [1, 3, 7].
These are the functions I created/use for removing duplicates:
var removeDuplicatesInPlace = function (arr) {
var i, j, cur, found;
for (i = arr.length - 1; i >= 0; i--) {
cur = arr[i];
found = false;
for (j = i - 1; !found && j >= 0; j--) {
if (cur === arr[j]) {
if (i !== j) {
arr.splice(i, 1);
}
found = true;
}
}
}
return arr;
};
var removeDuplicatesGetCopy = function (arr) {
var ret, len, i, j, cur, found;
ret = [];
len = arr.length;
for (i = 0; i < len; i++) {
cur = arr[i];
found = false;
for (j = 0; !found && (j < len); j++) {
if (cur === arr[j]) {
if (i === j) {
ret.push(cur);
}
found = true;
}
}
}
return ret;
};
So using the first one, this is how your code could look:
function cleanUp() {
var text = document.getElementById("fld"),
textVal = text.value,
array;
textVal = textVal.replace(/\r/g, " ");
array = textVal.split(/\n/g);
text.value = removeDuplicatesInPlace(array).join("\n");
}
DEMO: http://jsfiddle.net/VrcN6/1/
You can use Array.reduce() to remove the duplicates. You need a helper object to keep track of how many times an item has been seen.
function cleanUp()
{
var textBox = document.getElementById("fld"),
array = textBox.value.split(/\r?\n/g),
o = {},
output;
output = array.reduce(function(prev, current) {
var key = '$' + current;
// have we seen this value before?
if (o[key] === void 0) {
prev.push(current);
o[key] = true;
}
return prev;
}, []);
// write back the result
textBox.value = output.join("\n");
}
The output of the reduce() step can be used directly to populate the text area again, without affecting the original sort order.
Demo
You can do this easily with just an object:
function removeDuplicates(text) {
var seen = {};
var result = '';
for (var i = 0; i < text.length; i++) {
var char = text.charAt(i);
if (char in seen) {
continue;
} else {
seen[char] = true;
result += char;
}
}
return result;
}
function cleanUp() {
var elem = document.getElementById("fld");
elem.value = removeDuplicates(elem.value);
}
arr3 = [1, 2, 3, 2, 4, 5];
unique = [];
function findUnique(val)
{
status = '0';
unique.forEach(function(itm){
if(itm==val){
status=1;
}
})
return status;
}
arr3.forEach(function(itm){
rtn = findUnique(itm);
if(rtn==0)
unique.push(itm);
});
console.log(unique); // [1, 2, 3, 4, 5]

Find duplicates in an array and remove them out using javascript

how to find duplicates in an array and remove them using javascript?
To do this generically, you could use something like the following, which removes duplicates from the array in place. If you have an array that contains only strings or numbers, you could simplify this significantly.
var arrayContains = Array.prototype.indexOf ?
function(arr, val) {
return arr.indexOf(val) > -1;
} :
function(arr, val) {
var i = arr.length;
while (i--) {
if (arr[i] === val) {
return true;
}
}
return false;
}
function removeDuplicates(arr, equals) {
var val, originalArr = arr.slice(0);
arr.length = 0;
for (var i = 0, len = originalArr.length; i < len; ++i) {
val = originalArr[i];
if (!arrayContains(arr, val)) {
arr.push(val);
}
}
return arr;
}
var arr = [1, 2, 2, 1, 3];
removeDuplicates(arr);
console.log(arr); // [1, 2, 3]
var sampleArr=new Array(1,1,1,1,1,2,2,3,3,3,4,4,4); //Declare array
document.write(uniqueArr(sampleArr)); //Print the unique value
//Adds new uniqueArr values to temp array
function uniqueArr(a) {
temp = new Array();
for(i=0;i<a.length;i++){
if(!contains(temp, a[i])){
temp.length+=1;
temp[temp.length-1]=a[i];
}
}
return temp;
}
//Will check for the Uniqueness
function contains(a, e) {
for(j=0;j<a.length;j++)if(a[j]==e)return true;
return false;
}
for(var i=0; i < arr.length; i++)
{
for(var j=i+1; j < arr.length; j++)
{
if(arr[j] == arr[i])
{
arr.splice(j, 1);
}
}
}

Categories