Can't find a match - actionscript-3

I have a nested arrays with pairs of numbers:
_open = [[8,15], [9,16]];
from which i want to find a match using ArrayUtilities.findMatchIndex but it always returns -1 when looking for an element array. For example:
ArrayUtilities.findMatchIndex(_open, [8, 15])
I'm wondering if it is possible for AS3 to compare arrays, because comparing other types (strings, numbers, etc) just work fine
Here's findMatchIndex():
public static function findMatchIndex(aArray:Array, oElement:Object, ...rest):Number {
var nStartingIndex:Number = 0;
var bPartialMatch:Boolean = false;
if(typeof rest[0] == "number") {
nStartingIndex = rest[0];
}
else if(typeof rest[1] == "number") {
nStartingIndex = rest[1];
}
if(typeof rest[0] == "boolean") {
bPartialMatch = rest[0];
}
var bMatch:Boolean = false;
for(var i:Number = nStartingIndex; i < aArray.length; i++) {
if(bPartialMatch) {
bMatch = (aArray[i].indexOf(oElement) != -1);
}
else {
bMatch = (aArray[i] == oElement);
}
if(bMatch) {
return i;
}
}
return -1;
}

Comparing other types (strings, numbers, etc) works fine, because they are so-called primitives, and are compared by values. Arrays, though, are objects, therefore they are compared by reference. Basically it means that [8,15] != [8,15].
One way around it is replacing this line...
else {
bMatch = (aArray[i] == oElement);
}
... with something like this ...
else {
bMatch = compareElements(aArray[i], oElement);
}
... where compareElements will try to check its arguments' types first, and if they're objects, will compare their values.

Related

Doesn´t recognice as equal (==)

Can someone tell me why these variables marked with red are not recognized as equal (==).
Google Apps Script is Javascript-based. In Javascript, you can not compare two arrays using ==.
One method is to loop over both arrays and to check that the values are the same. For example you can include the function:
function compareArrays(array1, array2) {
for (var i = 0; i < array1.length; i++) {
if (array1[i] instanceof Array) {
if (!(array2[i] instanceof Array) || compareArrays(array1[i], array2[i]) == false) {
return false;
}
}
else if (array2[i] != array1[i]) {
return false;
}
}
return true;
}
And then update the line in your code from if (responsables == gestPor) { to if (compareArrays(responsables, gestPor)) {
For other methods of comparing arrays in Javascript, see this answer.
It is because you are comparing arrays. If you are just getting a single cell value, use getValue() instead of getValues()
To make things work, change these:
var gestPor = hojaActivador.getRange(i,13,1,1).getValues();
var responsables = hojaConMails.getRange(1,n,1,1).getValues();
to:
var gestPor = hojaActivador.getRange(i,13).getValue();
var responsables = hojaConMails.getRange(1,n).getValue();
Do these to all getValues() where you're only extracting 1 cell/value.
See difference below:

An empty array shows up non-empty when returned from function [duplicate]

This question already has answers here:
How do I test for an empty JavaScript object?
(48 answers)
Closed 5 years ago.
What is the fastest way to check if an object is empty or not?
Is there a faster and better way than this:
function count_obj(obj){
var i = 0;
for(var key in obj){
++i;
}
return i;
}
For ECMAScript5 (not supported in all browsers yet though), you can use:
Object.keys(obj).length === 0
I'm assuming that by empty you mean "has no properties of its own".
// Speed up calls to hasOwnProperty
var hasOwnProperty = Object.prototype.hasOwnProperty;
function isEmpty(obj) {
// null and undefined are "empty"
if (obj == null) return true;
// Assume if it has a length property with a non-zero value
// that that property is correct.
if (obj.length > 0) return false;
if (obj.length === 0) return true;
// If it isn't an object at this point
// it is empty, but it can't be anything *but* empty
// Is it empty? Depends on your application.
if (typeof obj !== "object") return true;
// Otherwise, does it have any properties of its own?
// Note that this doesn't handle
// toString and valueOf enumeration bugs in IE < 9
for (var key in obj) {
if (hasOwnProperty.call(obj, key)) return false;
}
return true;
}
Examples:
isEmpty(""), // true
isEmpty(33), // true (arguably could be a TypeError)
isEmpty([]), // true
isEmpty({}), // true
isEmpty({length: 0, custom_property: []}), // true
isEmpty("Hello"), // false
isEmpty([1,2,3]), // false
isEmpty({test: 1}), // false
isEmpty({length: 3, custom_property: [1,2,3]}) // false
If you only need to handle ECMAScript5 browsers, you can use Object.getOwnPropertyNames instead of the hasOwnProperty loop:
if (Object.getOwnPropertyNames(obj).length > 0) return false;
This will ensure that even if the object only has non-enumerable properties isEmpty will still give you the correct results.
EDIT: Note that you should probably use ES5 solution instead of this since ES5 support is widespread these days. It still works for jQuery though.
Easy and cross-browser way is by using jQuery.isEmptyObject:
if ($.isEmptyObject(obj))
{
// do something
}
More: http://api.jquery.com/jQuery.isEmptyObject/
You need jquery though.
Underscore and lodash each have a convenient isEmpty() function, if you don't mind adding an extra library.
_.isEmpty({});
Lets put this baby to bed; tested under Node, Chrome, Firefox and IE 9, it becomes evident that for most use cases:
(for...in...) is the fastest option to use!
Object.keys(obj).length is 10 times slower for empty objects
JSON.stringify(obj).length is always the slowest (not surprising)
Object.getOwnPropertyNames(obj).length takes longer than Object.keys(obj).length can be much longer on some systems.
Bottom line performance wise, use:
function isEmpty(obj) {
for (var x in obj) { return false; }
return true;
}
or
function isEmpty(obj) {
for (var x in obj) { if (obj.hasOwnProperty(x)) return false; }
return true;
}
Results under Node:
first result: return (Object.keys(obj).length === 0)
second result: for (var x in obj) { return false; }...
third result: for (var x in obj) { if (obj.hasOwnProperty(x)) return false; }...
forth result: return ('{}' === JSON.stringify(obj))
Testing for Object with 0 keys
0.00018
0.000015
0.000015
0.000324
Testing for Object with 1 keys
0.000346
0.000458
0.000577
0.000657
Testing for Object with 2 keys
0.000375
0.00046
0.000565
0.000773
Testing for Object with 3 keys
0.000406
0.000476
0.000577
0.000904
Testing for Object with 4 keys
0.000435
0.000487
0.000589
0.001031
Testing for Object with 5 keys
0.000465
0.000501
0.000604
0.001148
Testing for Object with 6 keys
0.000492
0.000511
0.000618
0.001269
Testing for Object with 7 keys
0.000528
0.000527
0.000637
0.00138
Testing for Object with 8 keys
0.000565
0.000538
0.000647
0.00159
Testing for Object with 100 keys
0.003718
0.00243
0.002535
0.01381
Testing for Object with 1000 keys
0.0337
0.0193
0.0194
0.1337
Note that if your typical use case tests a non empty object with few keys, and rarely do you get to test empty objects or objects with 10 or more keys, consider the Object.keys(obj).length option. - otherwise go with the more generic (for... in...) implementation.
Note that Firefox seem to have a faster support for Object.keys(obj).length and Object.getOwnPropertyNames(obj).length, making it a better choice for any non empty Object, but still when it comes to empty objects, the (for...in...) is simply 10 times faster.
My 2 cents is that Object.keys(obj).length is a poor idea since it creates an object of keys just to count how many keys are inside, than destroys it! In order to create that object he needs to loop overt the keys... so why use it and not the (for... in...) option :)
var a = {};
function timeit(func,count) {
if (!count) count = 100000;
var start = Date.now();
for (i=0;i<count;i++) func();
var end = Date.now();
var duration = end - start;
console.log(duration/count)
}
function isEmpty1() {
return (Object.keys(a).length === 0)
}
function isEmpty2() {
for (x in a) { return false; }
return true;
}
function isEmpty3() {
for (x in a) { if (a.hasOwnProperty(x)) return false; }
return true;
}
function isEmpty4() {
return ('{}' === JSON.stringify(a))
}
for (var j=0;j<10;j++) {
a = {}
for (var i=0;i<j;i++) a[i] = i;
console.log('Testing for Object with '+Object.keys(a).length+' keys')
timeit(isEmpty1);
timeit(isEmpty2);
timeit(isEmpty3);
timeit(isEmpty4);
}
a = {}
for (var i=0;i<100;i++) a[i] = i;
console.log('Testing for Object with '+Object.keys(a).length+' keys')
timeit(isEmpty1);
timeit(isEmpty2);
timeit(isEmpty3);
timeit(isEmpty4, 10000);
a = {}
for (var i=0;i<1000;i++) a[i] = i;
console.log('Testing for Object with '+Object.keys(a).length+' keys')
timeit(isEmpty1,10000);
timeit(isEmpty2,10000);
timeit(isEmpty3,10000);
timeit(isEmpty4,10000);
Elegant way - use keys
var myEmptyObj = {};
var myFullObj = {"key":"value"};
console.log(Object.keys(myEmptyObj).length); //0
console.log(Object.keys(myFullObj).length); //1
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
function isEmpty( o ) {
for ( var p in o ) {
if ( o.hasOwnProperty( p ) ) { return false; }
}
return true;
}
var x= {}
var y= {x:'hi'}
console.log(Object.keys(x).length===0)
console.log(Object.keys(y).length===0)
true
false
http://jsfiddle.net/j7ona6hz/1/
Surprised to see so many weak answers on such a basic JS question... The top answer is no good too for these reasons:
it generates a global variable
returns true on undefined
uses for...in which is extremely slow by itself
function inside for...in is useless - return false without hasOwnProperty magic will work fine
In fact there's a simpler solution:
function isEmpty(value) {
return Boolean(value && typeof value === 'object') && !Object.keys(value).length;
}
https://lodash.com/docs#isEmpty comes in pretty handy:
_.isEmpty({}) // true
_.isEmpty() // true
_.isEmpty(null) // true
_.isEmpty("") // true
How bad is this?
function(obj){
for(var key in obj){
return false; // not empty
}
return true; // empty
}
No need for a library.
function(){ //must be within a function
var obj = {}; //the object to test
for(var isNotEmpty in obj) //will loop through once if there is a property of some sort, then
return alert('not empty')//what ever you are trying to do once
return alert('empty'); //nope obj was empty do this instead;
}
It might be a bit hacky. You can try this.
if (JSON.stringify(data).length === 2) {
// Do something
}
Not sure if there is any disadvantage of this method.
fast onliner for 'dictionary'-objects:
function isEmptyDict(d){for (var k in d) return false; return true}
You can write a fallback if Array.isArray and Object.getOwnPropertyNames is not available
XX.isEmpty = function(a){
if(Array.isArray(a)){
return (a.length==0);
}
if(!a){
return true;
}
if(a instanceof Object){
if(a instanceof Date){
return false;
}
if(Object.getOwnPropertyNames(a).length == 0){
return true;
}
}
return false;
}
Imagine you have the objects below:
var obj1= {};
var obj2= {test: "test"};
Don't forget we can NOT use === sign for testing an object equality as they get inheritance, so If you using ECMA 5 and upper version of javascript, the answer is easy, you can use the function below:
function isEmpty(obj) {
//check if it's an Obj first
var isObj = obj !== null
&& typeof obj === 'object'
&& Object.prototype.toString.call(obj) === '[object Object]';
if (isObj) {
for (var o in obj) {
if (obj.hasOwnProperty(o)) {
return false;
break;
}
}
return true;
} else {
console.error("isEmpty function only accept an Object");
}
}
so the result as below:
isEmpty(obj1); //this returns true
isEmpty(obj2); //this returns false
isEmpty([]); // log in console: isEmpty function only accept an Object
funtion isEmpty(o,i)
{
for(i in o)
{
return!1
}
return!0
}
here's a good way to do it
function isEmpty(obj) {
if (Array.isArray(obj)) {
return obj.length === 0;
} else if (typeof obj === 'object') {
for (var i in obj) {
return false;
}
return true;
} else {
return !obj;
}
}
var hasOwnProperty = Object.prototype.hasOwnProperty;
function isArray(a) {
return Object.prototype.toString.call(a) === '[object Array]'
}
function isObject(a) {
return Object.prototype.toString.call(a) === '[object Object]'
}
function isEmpty(a) {
if (null == a || "" == a)return!0;
if ("number" == typeof a || "string" == typeof a)return!1;
var b = !0;
if (isArray(a)) {
if (!a.length)return!0;
for (var c = 0; c < a.length; c++)isEmpty(a[c]) || (b = !1);
return b
}
if (isObject(a)) {
for (var d in a)hasOwnProperty.call(a, d) && (isEmpty(a[d]) || (b = !1));
return b
}
return!0
}
May be you can use this decision:
var isEmpty = function(obj) {
for (var key in obj)
if(obj.hasOwnProperty(key))
return false;
return true;
}
I modified Sean Vieira's code to suit my needs. null and undefined don't count as object at all, and numbers, boolean values and empty strings return false.
'use strict';
// Speed up calls to hasOwnProperty
var hasOwnProperty = Object.prototype.hasOwnProperty;
var isObjectEmpty = function(obj) {
// null and undefined are not empty
if (obj == null) return false;
if(obj === false) return false;
if(obj === true) return false;
if(obj === "") return false;
if(typeof obj === "number") {
return false;
}
// Assume if it has a length property with a non-zero value
// that that property is correct.
if (obj.length > 0) return false;
if (obj.length === 0) return true;
// Otherwise, does it have any properties of its own?
// Note that this doesn't handle
// toString and valueOf enumeration bugs in IE < 9
for (var key in obj) {
if (hasOwnProperty.call(obj, key)) return false;
}
return true;
};
exports.isObjectEmpty = isObjectEmpty;
here my solution
function isEmpty(value) {
if(Object.prototype.toString.call(value) === '[object Array]') {
return value.length == 0;
} else if(value != null && typeof value === 'object') {
return Object.getOwnPropertyNames(value).length == 0;
} else {
return !(value || (value === 0));
}
}
Chears
if (Object.getOwnPropertyNames(obj1).length > 0)
{
alert('obj1 is empty!');
}

Check to see if two strings are anagrams of each other in JavaScript. What logic is used here?

Can someone help explain the logic used in the JavaScript code here?
The code below checks to see if two strings are anagrams of each other, but I don't understand the method being used to check the string.
Thanks.
<script type="text/javascript">
$(document).ready(function() {
var anagram = function(str1, str2){
if (str1.length !== str2.length) {
return false;
}
var sortstr1 = str1.split('').sort().join('');
var sortstr2 = str2.split('').sort().join('');
return (sortstr1 === sortstr2);
}
$('.AnagramChecker').on('click', function(e) {
e.preventDefault();
if($('#string1').val() == '') {
$('#string1').addClass('error');
if($('#string2').val() == '') {
$('#string2').addClass('error');
}
$('.results').empty();
$('.results').hide();
} else {
$('#string1').removeClass('error');
if($('#string2').val() == '') {
$('#string2').addClass('error');
$('.results').empty();
$('.results').hide();
} else {
$('#string2').removeClass('error');
var isAnagram = anagram($('#string1').val(), $('#string2').val());
$('#string1').val('');
$('#string2').val('')
$('.results').show();
$('.results').empty().append('Anagram is: ' + isAnagram);
}
}
});
});
</script>
Both strings are being split down into arrays of their individual characters, which are then sorted alphabetically and joined again into strings. The strings are then compared, and if they are the same, are anagrams of one another.
function anagrams(str1,str2){
//spliting string into array
let arr1 = str1.split("");
let arr2 = str2.split("");
//verifying array lengths
if(arr1.length !== arr2.length){
return false;
}
//creating objects
let frqcounter1={};
let frqcounter2 ={};
// looping through array elements and keeping count
for(let val of arr1){
frqcounter1[val] =(frqcounter1[val] || 0) + 1;
}
for(let val of arr2){
frqcounter2[val] =(frqcounter2[val] || 0) + 1;
}
console.log(frqcounter1);
console.log(frqcounter2);
//loop for every key in first object
for(let key in frqcounter1){
//if second object does not contain same frq count
if(frqcounter2[key] !== frqcounter1[key]){
return false;
}
}
return true;
}
anagrams('anagrams','nagramas');
function compare(a1,a2){
if(a1.length != a2.length){
return false
}
var f1 = {}, f2 ={};
for(var a of a1){
f1[a] = ++f1[a] || 1
}
for(var a of a2){
f2[a] = ++f2[a] || 1
}
for(var key in f1){
if(!(key in f2)){
return false
}
if(f1[key] != f2[key]) {
return false
}
}
return true
}

How to merge two arraycollection and without duplicates?

I want merge 2 array collection, where no duplicates are allowed,
var ac1:ArrayCollection = new ArrayCollection([ {s:"4",e:"8"}, {s:"9",e:"10"}, ]);
var ac2:ArrayCollection = new ArrayCollection([ {s:"2",e:"3"}, {s:"4",e:"8"}, {s:"9",e:"10"}, {s:"11",e:"12"}, ]);
how can I do it in efficient way
Thanks,
Errr, I'm not an actionscript guy but it's a classic problem - sort the two arrays in ascending order, then feed them into your third array, always selecting the lowest value from the two source arrays and escaping the write to the destination if what you would write is already at the end of the list - you'll end up with a sorted list of the unique values in the n input arrays
For more properties, use something like:
function equals(o1:Object, o2:Object):Boolean
{
if (o1 == o2) return true;
if (!o1 || !o2) return false;
for (var key:String in o1)
{
if (!(key in o2)) return false;
if (o1[key] != o2[key]) return false;
}
return true;
}
Perhaps this is a good starter.
function equals(o1:Object, o2:Object)
{
return (o1 && o2) && (o1 != o2) && (o1.s != o2.s) && (o1.e != o2.e);
}
function merge(a:Array, b:Array):Array
{
const source = [];
var isContained:Boolean = false;
for (var i:int; i< a.length;i++) {
isContained = false
for (var j:int; j< b.length;j++) {
if (equals(a[i], b[j])) {
isContained = true;
break;
}
}
if (!isContained) {
source.push(a[1]);
}
}
return source.concat(b);
}

How can I use a custom function with FILTER?

I have a custom function defined that extracts part of an address from a string:
/*
* Return the number preceding 'N' in an address
* '445 N 400 E' => '445'
* '1083 E 500 N' => '500'
*/
function NorthAddress(address) {
if (!address) return null;
else {
var North = new RegExp('([0-9]+)[\\s]+N');
var match = address.match(North);
if (match && match.length >= 2) {
return match[1];
}
return null;
}
}
I want to use this function as one of the conditions in a call to FILTER(...) in the spreadsheet where I have these addresses stored:
=FILTER('Sheet 1'!A:A, NorthAddress('Sheet 1'!B:B) >= 450))
But when I call NorthAddress like this, it gets an array of all the values in column B and I can't for the life of me find any documentation as to how I need to handle that. The most obvious way (to me) doesn't seem to work: iterate over the array calling NorthAddress on each value, and return an array of the results.
What does my function need to return for FILTER to work as expected?
When a custom function is called passing a multi-cell range, it receives a matrix of values (2d array), it's doesn't matter if the range is a single column or a single row, it's always a matrix. And you should return a matrix as well.
Anyway, I would not use a custom function to this, as there is already the native spreadsheet formulas: RegexMatch, RegexExtract and RegexReplace formulas. To get the "if match" behavior, just wrap them in a IfError formula.
It doesn't work because address is, if you pass only one cell as arg a string, a range, a matrix of string.
So you return a string, FILTER use a boolean array to filter data, so the condition of your filter is string < number.
You just have to convert the string to a number when you returning a value
/*
* Return the number preceding 'N' in an address
* '445 N 400 E' => '445'
* '1083 E 500 N' => '500'
*/
function NorthAddress(address) {
if(typeof address == "string"){
if (!address) return "#N/A";
else {
var North = new RegExp('([0-9]+)[\\s]+N');
var match = address.match(North);
if (match && match.length >= 2) {
return parseInt(match[1]);
}
return "#N/A";
}
} else {
var matrix = new Array();
for(var i = 0; i<address.length; i++){
matrix[i] = new Array();
for(var j = 0; j<address[i].length; j++){
var North = new RegExp('([0-9]+)[\\s]+N');
var match = address[i][j].match(North);
if (match && match.length >= 2) {
matrix[i].push(parseInt(match[1]));
}
}
}
return matrix;
}
}
Hope this will help.
I will add this as an answer, because I found the custom function returns an error if numerical values are passed in the referenced cell or range when toString() is not invoked:
function NorthAddress(address) {
if (!address) return null;
else {
if (address.constructor == Array) {
var result = address;
}
else {
var result = [[address]];
}
var north = new RegExp('([0-9]+)[\\s]+N');
var match;
for (var i = 0; i < result.length; i++) {
for (var j = 0; j < result[0].length; j++) {
match = result[i][j].toString().match(north);
if (match && match.length >= 2) {
result[i][j] = parseInt(match[1]);
}
else {
result[i][j] = null;
}
}
}
return result;
}
}