For variables in document (Javascript) - javascript

This code isn't completely finished yet. I'm trying to iterate over all 'm' variables within a page until there are no more 'm's within the page. Right now I have 'for (m in document)', which I know to be wrong. Can anyone point me in the right direction for the correct syntax?
var m = document.getElementsByClassName('project')
var n = document.getElementsByClassName('web')
var o = document.getElementsByClassName('print')
var p = document.getElementsByClassName('illustration')
function projectFilter(type){
if (type === 'print'){
for (m in document){
if (getElementsByClassName('print') != null){
m.style(opacity=0.3)
console.log("Whatshappening")
}
}
if (type === 'web'){
console.log('webbyshit')
}
if (type === 'illustration'){
console.log('illustrating')
}
if (type === 'project'){
console.log('EVERYTHING')
}
}
Thank you!

You already have m defined at the top of your script, so you don't have to look for it in document. Just loop it like you would loop an array (m is a NodeList object, but it has a length property like arrays do):
for(var i=0; i<m.length; i++) {
// do something with each m[i]
}

Three problems
you are iterating incorrectly
your style assignment is incorrect:
getElementsByClassName will always return an object, even if it is an empty set. Check its length property to see if you get any elements back.
for (var i = 0, len = m.length; i<len; i++) {
if (m[i].getElementsByClassName('print').length > 0 ){
m.style.opacity=0.3;
}
}

Related

Sort function that uses an integer array argument doesnt work

I'm a beginner trying to learn JS, I've got some basic knowledge.
I wrote a function to realize insertion sort on a given array (the array is passed on to the function as a parameter).
When I initialize the array and give it value, e.g,
sampleArray = [1,35,73,234,1,1,356];
and pass that to my function, it works perfectly.
however, if I try to pass on an array filled by user input - or an array that was merged out of two given arrays (my original assignment),
it doesn't work - no exceptions or errors, it just... doesn't sort as expected.
I've been racking my mind over this, maybe I don't know where to look?
function sortArray(arrT) {
for (let i = 1; i < arrT.length; i++){
var tempMax = arrT[i];
var j = i - 1;
while ((j >= 0) && (arrT[j] > tempMax)) {
console.log(arr1 + "\nj=" + j + " i=" + i);
arrT[j+1] = arrT[j];
j--;
}
arrT[j+1] = tempMax;
}
console.log("sorted array is (inside loop) :\n" +arrT);
return arrT;
}
for an array that was filled by a while loop of prompts such as
it's equal to the above sample array, the result is
1,1,1,234,35,356,73
for reference, though it's far from elegant, I'm using this to fill the array:
for (let i = 0, x = ""; x !== "x"; i++) {
x = prompt("press x to finish, enter to continue");
if (x == "x") { break }
arr1[i]=prompt("enter");
}
As per my understanding.
The mistake is here
Original Code:
for (let i = 0, x = ""; x !== "x"; i++) {
x = prompt("press x to finish, enter to continue");
if (x == "x") { break }
arr1[i]=prompt("enter");//do not use prompts while unnecessary. Just replace it with x;
}
Corrected One:
for (let i = 0, x = ""; x !== "x"; i++) {
x = prompt("press x to finish, enter to continue");
if (x == "x") { break }
/*
you can also improve your code by applying few checks
if(!isNaN(x)) continue; // --- to skip when input value isn't a number
*/
arr1[i]=x;
}
for (let i = 0, x = ""; x !== "x"; i++) {
x = prompt("press x to finish, enter to continue");
if (x == "x") { break }
arr1[i]=prompt("enter");
}
prompt actually returns a string, hence your input is an array of strings instead. You should use Number to ensure the provided value is numeric.
I would rewrite the above in this way:
// stores all the values.
var arr1 = [];
// Stores the current value.
var input;
do {
var _ = prompt("press x to finish, enter to continue"); // <-- not sure why you're doing that every time, I would suggest you to move it outside of the loop.
input = prompt("enter");
var n = Number(input);
if (!isNaN(n)) arr1.push(n); // <-- checks whether the provided value is actually numeric and a valid number. If it is, the value is added to the collection.
}
while (input !== 'x');
console.log(arr1);
I would suggest you to move the first prompt outside of the loop, but since you did it in your code, I suspect there is a reason for that, though I don't get it.
In any case, the above sample will check whether the value passed is valid; if it is, it push the item to the collection, otherwise it continues until 'x' is met.

Compare 2 records on screen with javascript

Im looking for a way to compare 2 json records on screen. The way i want is that, i want to show these 2 records side by side and mark the matched or unmatched properties.
Is there a library that does it already, and if not, how can i do it ??
Edit
My goal is to identify the same/different properties & to show them to users with different styles, rather than comparing the objects as a whole.
Someone made a jQuery plugin for this - jQuery.PrettyTextDiff.
https://github.com/arnab/jQuery.PrettyTextDiff
$("input[type=button]").click(function () {
$("#wrapper tr").prettyTextDiff({
cleanup: $("#cleanup").is(":checked")
});
});
JSFiddle
Here is a quick JavaScript function to help you compare the to JSON strings.
First, it checks that they have same number of properties, then compares that they have the same properties (by name) and then it compares the values.
You may want to tweak the value comparison (to allow for undefined or null).
Hope it is a good starter for you.
<script type="text/javascript">
var so = {}; // stackoverflow, of course.
so.compare = function (left, right) {
// parse JSON to JavaScript objects
var leftObj = JSON.parse(left);
var rightObj = JSON.parse(right);
// add object properties to separate arrays.
var leftProps = [];
var rightProps = [];
for(var p in leftObj) { leftProps.push(p); }
for(var p in rightObj) { rightProps.push(p); }
// do they have the same number of properties
if (leftProps.length != rightProps.length) return false;
// is every right property found on the left
for (var r = 0; r < rightProps.length; r++) {
var prop = rightProps[r];
if (leftProps.indexOf(prop) < 0) {
return false;
}
}
// is every left property found on the right
for (var r = 0; r < leftProps.length; r++) {
var prop = leftProps[r];
if (rightProps.indexOf(prop) < 0) {
return false;
}
}
// do the values match?
for (var q = 0; q < leftProps.length; q++) {
var propname = leftProps[q];
var leftVal = leftObj[propname];
var rightVal = rightObj[propname];
if (leftVal != rightVal) {
return false;
}
}
return true;
}
</script>

Does a value exist in an Array not working?

So, I have this function it takes two arrays of objects, workArr and arr, and match there id property and then add up the hours property to store in the workArr array.
var workArr = [];
var arr = [];
foundID = [];
function blah()
{
var i = 0;
var j = 0;
//Add up the hours
for( i=0; i < workArr.length ; i++)
{
for( j=0; j < arr.length ; j++)
{
//Makesure the id's match and the week is within the given time frame
//ALSO make sure the id hasn't already be visited
if( cond1 && !(isInArray(workArr[i].id)))
{
workArr[j].total = workArr[j].total + arr[j].hrs;
foundId.push(workArr[j].id);
}//end if id === id
}//end for j loop
}//end for i loop
printArr(foundId);
}//End blah()
//Checks if the given id has already be found
//returns true or false
function isInArray(id) {
return foundID.indexOf(id) > -1;
}
The problem is when I print out my already visited id array, once this function ends, there are duplicates in it, and there shouldn't be because if a duplicate is found it breaks the if condition and doesn't get added to the already found id's. So somehow my if condition isn't weeding out the already visited id's. Please help me solve this seemingly easy problem.
Solved with the help from the comments should be workArr[i] not workArr[j]
if( cond1 && !(isInArray(workArr[i].id)))
{
workArr[i].total = workArr[i].total + arr[j].hrs; // workArr[i]
foundId.push(workArr[i].id); // workArr[i]
}//end if id === id

Compare property value in an array of objects

Hello I am working in a project to keep learning js wich is in this URL: http://themapapp.herokuapp.com/ and this is the github page: https://github.com/xtatanx/mapApp
In some of the parts of my code I need to check if some property already exists in an array of objects and also I that property value is equal to something, so far the code that I am using to to dis is this one:
// check if property value exist in an array of objects
function searchByValue(value, property, array){
for(var i = 0; i < array.length; i++){
if(array[i][property] === value){
return true;
}
}
return false;
}
And I use it like this:
if(searchByValue('myDestiny', 'id', map.markers)){
map.markers[1].setPosition({
lat: results[0].geometry.location.k,
lng: results[0].geometry.location.A
});
}else{
createMarker(results[0].geometry.location.k, results[0].geometry.location.A, 'myDestiny');
My question is if actually I am doing it the way it is or if I am wrong because I sometime think that the function its not returning the correct value or is not working good, I will appreciate if some of you guys could give me some advice in how to achieve this, or improve it.
EDIT
i finished with something like
Array.prototype.searchBy = function(property, value){
var _property = arguments[0];
var _value = arguments[1];
if(arguments.length === 1){
return Array.prototype.indexOf.apply(this, arguments);
}
for(var i = 0; i < this.length; i++){
if(this[i][_property] === _value ){
return true;
}
}
return false;
};
Didnt used the checkprop part because actually doesnt understood how it works o_O. thank you very much to #GameAlchemist and #jshanley
Your code works well as long as every object in the array you are searching has defined the property you check for. I could see running into a problem otherwise. You might try adding a check that the property is defined before trying to access its value, like this:
function searchByValue(value, property, array){
for(var i = 0; i < array.length; i++){
// check that property is defined first
if(typeof array[i][property] !== 'undefined') {
// then check its value
if(array[i][property] === value){
return true;
}
}
}
return false;
}
I would rather define this function as a method of Array, and why not overload indexOf, that would act as std indexOf with one argument, and as indexOf(value, propertyName, checkProp) with three arguments.
var __oldIndexOf = Array.prototype.indexOf ;
Array.prototype.indexOf = function() {
if (arguments.length==1) return __oldIndexOf.apply(this, arguments);
var value = arguments[0];
var property = arguments[1];
var checkProp = arguments[2];
if (!checkProp) {
for(var i = 0; i < this.length; i++){
if(this[i][property] === value){
return i;
}
} else {
for(var i = 0; i < this.length; i++){
var thisItem = this[i] ;
if (!Object.hasOwnProperty(thisItem, property))
throw('indexOf error : object ' + thisItem + ' has no property ' + property);
if(this[i][property] === value){
return i;
}
}
return -1;
};
so, for your code,
if (searchByValue('myDestiny', 'id', map.markers)) { ...
becomes :
if (map.markers.indexOf('myDestiny', 'id') != -1 ) { ...
and obviously you can store the found index in case you need it.
i think that, in your case, what you meant was rather using the found index :
var destinyIndex = map.markers.indexOf('myDestiny', 'id');
if(destinyIndex != -1){
map.markers[ destinyIndex ].setPosition({
lat: results[0].geometry.location.k,
lng: results[0].geometry.location.A
});
} else {
createMarker(results[0].geometry.location.k, results[0].geometry.location.A,
'myDestiny');
}
Edit : idea of checking that property exists is courtesy of #jshanley

JavaScript is in array [duplicate]

This question already has answers here:
How do I check if an array includes a value in JavaScript?
(60 answers)
Closed 28 days ago.
Let's say I have this:
var blockedTile = new Array("118", "67", "190", "43", "135", "520");
There's more array elements but those are just few for readability purposes. Anyways, I could do a "for" loop but it would do 500 loops everytime you click on the map... is there any other way to see if a certain string is in an array?
Try this:
if(blockedTile.indexOf("118") != -1)
{
// element found
}
As mentioned before, if your browser supports indexOf(), great!
If not, you need to pollyfil it or rely on an utility belt like lodash/underscore.
Just wanted to add this newer ES2016 addition (to keep this question updated):
Array.prototype.includes()
if (blockedTile.includes("118")) {
// found element
}
Some browsers support Array.indexOf().
If not, you could augment the Array object via its prototype like so...
if (!Array.prototype.indexOf)
{
Array.prototype.indexOf = function(searchElement /*, fromIndex */)
{
"use strict";
if (this === void 0 || this === null)
throw new TypeError();
var t = Object(this);
var len = t.length >>> 0;
if (len === 0)
return -1;
var n = 0;
if (arguments.length > 0)
{
n = Number(arguments[1]);
if (n !== n) // shortcut for verifying if it's NaN
n = 0;
else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0))
n = (n > 0 || -1) * Math.floor(Math.abs(n));
}
if (n >= len)
return -1;
var k = n >= 0
? n
: Math.max(len - Math.abs(n), 0);
for (; k < len; k++)
{
if (k in t && t[k] === searchElement)
return k;
}
return -1;
};
}
Source.
function in_array(needle, haystack){
var found = 0;
for (var i=0, len=haystack.length;i<len;i++) {
if (haystack[i] == needle) return i;
found++;
}
return -1;
}
if(in_array("118",array)!= -1){
//is in array
}
Use Underscore.js
It cross-browser compliant and can perform a binary search if your data is sorted.
_.indexOf
_.indexOf(array, value, [isSorted]) Returns the index at which value can be found in the array, or -1 if value is not present in the array.
Uses the native indexOf function unless it's missing. If you're
working with a large array, and you know that the array is already
sorted, pass true for isSorted to use a faster binary search.
Example
//Tell underscore your data is sorted (Binary Search)
if(_.indexOf(['2','3','4','5','6'], '4', true) != -1){
alert('true');
}else{
alert('false');
}
//Unsorted data works to!
if(_.indexOf([2,3,6,9,5], 9) != -1){
alert('true');
}else{
alert('false');
}
if(array.indexOf("67") != -1) // is in array
Assuming that you're only using the array for lookup, you can use a Set (introduced in ES6), which allows you to find an element in O(1), meaning that lookup is sublinear. With the traditional methods of .includes() and .indexOf(), you still may need to look at all 500 (ie: N) elements in your array if the item specified doesn't exist in the array (or is the last item). This can be inefficient, however, with the help of a Set, you don't need to look at all elements, and instead, instantly check if the element is within your set:
const blockedTile = new Set(["118", "67", "190", "43", "135", "520"]);
if(blockedTile.has("118")) {
// 118 is in your Set
console.log("Found 118");
}
If for some reason you need to convert your set back into an array, you can do so through the use of Array.from() or the spread syntax (...), however, this will iterate through the entire set's contents (which will be O(N)). Sets also don't keep duplicates, meaning that your array won't contain duplicate items.
I'd use a different data structure, since array seem to be not the best solution.
Instead of array, use an object as a hash-table, like so:
(posted also in jsbin)
var arr = ["x", "y", "z"];
var map = {};
for (var k=0; k < arr.length; ++k) {
map[arr[k]] = true;
}
function is_in_map(key) {
try {
return map[key] === true;
} catch (e) {
return false;
}
}
function print_check(key) {
console.log(key + " exists? - " + (is_in_map(key) ? "yes" : "no"));
}
print_check("x");
print_check("a");
Console output:
x exists? - yes
a exists? - no
That's a straight-forward solution. If you're more into an object oriented approach, then search Google for "js hashtable".
IMHO most compatible with older browsers
Array.prototype.inArray = function( needle ){
return Array(this).join(",").indexOf(needle) >-1;
}
var foods = ["Cheese","Onion","Pickle","Ham"];
test = foods.inArray("Lemon");
console.log( "Lemon is " + (test ? "" : "not ") + "in the list." );
By turning an Array copy in to a CSV string, you can test the string in older browsers.
Depending on the version of JavaScript you have available, you can use indexOf:
Returns the first index at which a given element can be found in the array, or -1 if it is not present.
Or some:
Tests whether some element in the array passes the test implemented by the provided function.
But, if you're doing this sort of existence check a lot you'd be better of using an Object to store your strings (or perhaps an object as well as the Array depending on what you're doing with your data).
in array example,Its same in php (in_array)
var ur_fit = ["slim_fit", "tailored", "comfort"];
var ur_length = ["length_short", "length_regular", "length_high"];
if(ur_fit.indexOf(data_this)!=-1){
alert("Value is avail in ur_fit array");
}
else if(ur_length.indexOf(data_this)!=-1){
alert("value is avail in ur_legth array");
}
var myArray = [2,5,6,7,9,6];
myArray.includes(2) // is true
myArray.includes(14) // is false
Why don't you use Array.filter?
var array = ['x','y','z'];
array.filter(function(item,index,array){return(item==YOURVAL)}).
Just copy that into your code, and here you go:
Array.prototype.inArray = function (searchedVal) {
return this.filter(function(item,index,array){return(item==searchedVal)}).length==true
}
You can try below code. Check http://api.jquery.com/jquery.grep/
var blockedTile = new Array("118", "67", "190", "43", "135", "520");
var searchNumber = "11878";
arr = jQuery.grep(blockedTile, function( i ) {
return i === searchNumber;
});
if(arr.length){ console.log('Present'); }else{ console.log('Not Present'); }
check arr.length if it's more than 0 means string is present else it's not present.
a little bit code from my side (custom function for Array):
Array.prototype.in_array = function (array) {
var $i = 0;
var type = typeof array;
while (this[$i]) {
if ((type == ('number') || type == ('string')) && array == this[$i]) {
return true;
} else if (type == 'object' && array instanceof Array && array.in_array(this[$i])) {
return true
}
$i++;
}
return false;
};
var array = [1, 2, 3, "a", "b", "c"];
//if string in array
if (array.in_array('b')) {
console.log("in array");
}
//if number in array
if (array.in_array(3)) {
console.log("in array");
}
// if one from array in array
if (array.in_array([1, 'b'])) {
console.log("in array");
}
I think the simplest way is that :
(118 in blockedTile); //is true

Categories