How to use Javascript array.find() with two conditions? - javascript

I need to check if any object in an array of objects has a type: a AND if another has a type: b
I initially did this:
const myObjects = objs.filter(attr => attr.type === 'a' || attr.type === 'b');
But the code review complained that filter will keep going through the entire array, when we just need to know if any single object meets either criteria.
I wanted to use array.find() but this only works for a single condition.
Is there anyway to do this without using a for loop?

you can pass two condition as given below
[7,5,11,6,3,19].find(attr => {
return (attr > 100 || attr %2===0);
});
6
[7,5,102,6,3,19].find(attr => {
return (attr > 100 || attr %2===0);
});
102

Updated answer:
It's not possible to shortcircuit js's builtin functions that does what you want, so you will have to use some kind of loop:
let a;
let b;
for (const elm of objs) {
if (!a && elm === 'a') {
a = elm;
}
if (!b && elm === 'b') {
b = elm;
}
const done = a && b;
if (done) break;
}
Also you should consider if you can record a and b when producing the array if that's possible.
Oiginal answer:
`find` works just like `filter` where it takes a predicate, returns the first element that the predicate returns `true`.
If I understood your question correctly, you can just replace the `filter` with `find` and it will return at the first occurance:
const myObject = objs.find(attr => attr.type === 'a' || attr.type === 'b');
Also notice your provided snippet is wrong for what you described: `filter` returns an array but you only wanted one element. so you should add `[0]` to the filter expression if you want to use it.

Related

lodash's isElement equivalent in pure JS

Right now I am using isElement by lodash to check if an element is DOM likely. I want to get rid of this library so I am looking for a pure JS implementation of this function.
I'm using this, but I don't know if it's the right implementation and if I'm ignoring any edge cases:
const isDOMElement = el => el instanceof HTMLElement
Update
I have tested (codepen link) the four proposed implementation, in all cases is working as expected, maybe the one proposed by #cesare covers most of the cases, but also the one proposed by #peter-seliger is clever and work with an "outside of the BOX" thinking. Finally, both #David Thomas and the one I firstly use, works for most of the cases.
So in conclusion I think, as David Thomas points It's just a matter of preference.
P.S: The tags used for the test are extracted from MDN's HTML elements reference
P.S2: Not sure on how to proceed and what answer accept. Both cesare and peter have a good point
One could give a try to ...
function exposeImplementation(value) {
return Object
.prototype
.toString
.call(value);
}
function getInternalClassName(value) {
return (/^\[object\s+(?<className>[^\]]+)\]$/)
.exec(
exposeImplementation(value)
)
?.groups
?.className;
}
function isHTMLElement(value) {
return !!value && (/^HTML(?:[A-Z][A-Za-z]+)?Element$/)
.test(
String(
getInternalClassName(value)
)
);
}
console.log(
getInternalClassName(document.createElement('h1')),
isHTMLElement(document.createElement('h1'))
);
console.log(
getInternalClassName(document.body),
isHTMLElement(document.body)
);
console.log(
getInternalClassName(document),
isHTMLElement(document)
);
.as-console-wrapper { min-height: 100%!important; top: 0; }
This is the lodash util:
function isElement(value) {
return isObjectLike(value) && value.nodeType === 1 && !isPlainObject(value)
}
Basically with isObjectLike it checks that the value passed is a non null object ( since null is an object in js ) and with !isPlainObject that it is not a plain object ( since it could be an object carrying a "nodeType": 1 entry and because an HTMLElement instance has nested protos.
The isPlainObject util is this:
function isPlainObject(value) {
if (!isObjectLike(value) || getTag(value) != '[object Object]') {
return false
}
if (Object.getPrototypeOf(value) === null) {
return true
}
let proto = value
while (Object.getPrototypeOf(proto) !== null) {
proto = Object.getPrototypeOf(proto)
}
return Object.getPrototypeOf(value) === proto
}
As you can see the first check is redundant since it checks isObjectLike again, but the main caveat in my opinion is that it doesn't cover other objects case, since for example "Arrays" are objects too hence they pass the check:
const arr = [1, 2]; // array
arr.nodeType = 1; // add nodeType property to the array object
console.log(isElement(arr)); // true Lodash
Try it yourself.
I think it's safer to check if the object has a nodeType property that is inherited:
const _isElement = (node) =>
typeof node === 'object' &&
node !== null &&
!node.hasOwnProperty('nodeType') &&
node.nodeType &&
node.nodeType === 1
const el = document.createElement('h1'); // node
const arr = [1, 2]; // array
arr.nodeType = 1; // add nodeType property to the array object
console.log(isElement(arr)); // true Lodash
console.log(isElement(el)); // true Lodash
console.log(_isElement(arr)) // false
console.log(_isElement(el)) // true
In any case I prefer using your check which already covers most of those checks since any primitive non object is not instance of HTMLElement, null is not instance of HTMLElement, and an HTMLElement instance has a "nodeType" poperty but it is inherited from proto and not an own property, :
const isDOMElement = el => el instanceof HTMLElement
//or
const isDOMElement = el => el instanceof Node
Look at the implementation from library source code:
https://github.com/lodash/lodash/blob/master/isElement.js

Arguments Object

i'm currently learning js and need to pass a test, every requirement checks out besides "should work on an arguments object".
So I need to use arguments[0]or[1], its also necessary for me to check if the array is an array. Issue here is that for some reason the Array.isArray() part of the code turns my "should work on an arguments object" requirement false, even though I used arguments[0].
please try to ignore the rest of the code, there are also other requirements set. I know they seem kind of unnecessary to include.
this is my code:
function (array, n) {
var resultArray = [];if (typeof arguments[1] !== "number" || arguments[1] == 0 || arguments[1] < 0){
resultArray.push.call(resultArray, arguments[0][0])
return resultArray
}
else if (arguments[1] > arguments[0].length){
return arguments[0] && array
} else {
return resultArray;
}
};
That's because the requirements expects you use somewhere the variable argument array. Instead you use arguments[0].
So use the first over the latter.
Likewise, use n instead of arguments[1]
You can use Array.prototype.slice function simply
const first = (array = [], n = 1) =>
Array.isArray(array) ? array.slice(0, array.length >= n ? n : 1) : [];
If n > array.length this will return the whole array.
Try this:
if (!window[atob('QXJyYXk=')][atob('aXNBcnJheQ==')](arguments[0])) return [];

Filter using lodash

I want to add element to array if there is no element with the same type and format.
I did it with for loop, but it looks bad.
for (i = 0; i < this.model.array.length; i++) {
const selectedElement = this.model.array[ i ]
if (selectedElement.value.format === item.value.format && selectedElement.value.type === item.value.type) {
this.model.array.splice(i, 1)
this.model.array.push(item)
break
}
if (i === this.model.array.length - 1) {
this.model.array.push(item)
}
}
Could you tell me how can I do this lodash filter?
I tried something like this:
let filter = _.filter(this.model.array, function (o) {
return ((o.value.type !== item.value.type) && (o.value.format !== item.value.format)) })
but it does not work, it returns 0 array every time.
My idea was to filter these elements (but it's just one) which type and format is the same as items and then push something using this filtered array.
Or maybe there is another way how can I add elements if condition is met?
Item looks like this:
You have the wrong boolean operation in your filter.
Consider your original condition to find matching entries in a loop:
selectedElement.value.format === item.value.format && selectedElement.value.type === item.value.type
Let's call the two tests (or "predicates") A and B, such that the expression reduces to:
A && B
Within your filter call you want to retain the entries that do not match, i.e.:
!(A && B)
which De Morgan's Laws say is equivalent to:
!A || !B
However what you've actually written is:
!A && !B
which is equivalent to:
!(A || B)

Efficient way to compare arrays in javascript

I need to compare the elements from two arrays as follows:
arr1[0] ? arr2[0]
arr1[1] ? arr2[1]
arr1[2] ? arr2[2]
etc.
I wrote some code but it seems to be slow when I try to compare 1000 objects like this on each array :
{
"id":"event707",
"name":"Custom707",
"type":"disabled",
"default_metric":false,
"participation":"disabled",
"serialization":"always_record"
}
This is how my function looks like (just an example for two arrays with hard coded data).
function compare() {
var step = 0;
var fruits1 = [{"apple":25},{"bannana":36},{"orange":6}];
var fruits2 = [{"apple":25},{"bannana":36},{"orange":6}];
for(var i=0;i<fruits1.length;i++) {
for(var j=step;j<fruits2.length;j++) {
console.log("FRUIT1");
console.log(JSON.stringify(fruits1[i]));
console.log("FRUIT2");
console.log(JSON.stringify(fruits2[j]));
console.log("----------------------");
if(JSON.stringify(fruits1[i])!== JSON.stringify(fruits2[j])) {
//do something
}
step = step + 1;
break;
}
}
}
With an invention of Object.prototype.compare() and Array.prototype.compare() this job becomes a very simple task. Array compare can handle both primitive and reference type items. Objects are compared shallow. Let's see how it works;
Object.prototype.compare = function(o){
var ok = Object.keys(this);
return typeof o === "object" && ok.length === Object.keys(o).length ? ok.every(k => this[k] === o[k]) : false;
};
Array.prototype.compare = function(a){
return this.every((e,i) => typeof a[i] === "object" ? a[i].compare(e) : a[i] === e);
};
var fruits1 = [{"apple":25},{"bannana":36},{"orange":6}],
fruits2 = [{"apple":25},{"bannana":36},{"orange":6}];
console.log(fruits1.compare(fruits2));
Simple function without library:
var arr1 = [1,2,3];
var arr2 = [1,2,4];
//This function takes one item, the index of the item, and another array to compare the item with.
function compare(item, index, array2){
return array2[index] == item;
}
// the forEach method gives the item as first parameter
// the index as second parameter
// and the array as third parameter. All are optional.
arr1.forEach(function(item, index){
console.log(compare(item, index, arr2));
});
Combine this with the answer Abdennour TOUMI gave, and you have an object comparison method :)
For simple objects you could use JSON.stringify(obj1) === JSON.stringify(obj2).
More info on object comparison can be found in this answer
Use underscore array functions. I would go with intersection
http://underscorejs.org/#intersection
You can use the following static method for Object class : Object.equals
Object.equals=function(a,b){if(a===b)return!0;if(!(a instanceof Object&&b instanceof Object))return!1;if(a.valueOf()===b.valueOf())return!0;if(a.constructor!==b.constructor)return!1;for(var c in a)if(a.hasOwnProperty(c)){if(!b.hasOwnProperty(c))return!1;if(a[c]!==b[c]){if("object"!=typeof a[c])return!1;if(!Object.equals(a[c],b[c]))return!1}}for(c in b)if(b.hasOwnProperty(c)&&!a.hasOwnProperty(c))return!1;return!0};
console.log(
`"[1,2,3] == [1,2,3]" ?`,Object.equals([1,2,3],[1,2,3])
);
console.log(
`"[{"apple":25},{"bannana":36},{"orange":6}] == [{"apple":25},{"bannana":36},{"orange":6}]" ?`,Object.equals([{"apple":25},{"bannana":36},{"orange":6}], [{"apple":25},{"bannana":36},{"orange":6}])
);

Sort Array B after Array A, such that references and equal Primitives, maintain the exact Position

Update 2
I added a weight lookup to the sort function, which increased the performance by about 100% as well as the stability, as the previous sort function didn't consider all types, and as 1 == "1" the result depends on the initial order of the Array, as #Esailija points out.
The intent of the question is to improve this Answer of mine, I liked the question and since it got accepted and I felt like there is some performance to squeeze out of the sort function. I asked this question here since I hadn't many clues left where to start.
Maybe this makes things clearer as well
Update
I rephrased the complete question, as many people stated I was not specific enough, I did my best to specify what I mean. Also, I rewrote the sort function to better express the intent of the question.
Let arrayPrev be an Array (A) ,where A consists of 0 to n Elements' (E)
Let an Element either be
of a Primitive type
boolean, string, number, undefined, null
a Reference to an Object O, where O.type = [object Object] and O can consist of
0 to n Properties P, where P is defined like Element plus
an circular Reference to any P in O
Where any O can be contained 1 to n times. In the sense of GetReferencedName(E1) === GetReferencedName(E2)...
a Reference to an O, where O.type = [object Array] and O is defined like A
a circular Reference to any E in A
Let arrayCurr be an Array of the same length as arrayPrev
Illustrated in the following example
var x = {
a:"A Property",
x:"24th Property",
obj: {
a: "A Property"
},
prim : 1,
}
x.obj.circ = x;
var y = {
a:"A Property",
x:"24th Property",
obj: {
a: "A Property"
},
prim : 1,
}
y.obj.circ = y;
var z = {};
var a = [x,x,x,null,undefined,1,y,"2",x,z]
var b = [z,x,x,y,undefined,1,null,"2",x,x]
console.log (sort(a),sort(b,a))
The Question is, how can I efficiently sort an Array B, such that any Reference to an Object or value of a Primitive, shares the exact same Position as in a Previously, by the same compareFunction, sorted, Array A.
Like the above example
Where the resulting array shall fall under the rules.
Let arrayPrev contain the Elements' of a and arrayCurr contain the Elements' of b
Let arrayPrev be sorted by a CompareFunction C.
Let arrayCurr be sorted by the same C.
Let the result of sorting arrayCur be such, that when accessing an E in arrayCur at Position n, let n e.g be 5
if type of E is Object GetReferencedName(arrayCurr[n]) === GetReferencedName(arrayPrev[n])
if type of E is Primitive GetValue(arrayCurr[n]) === GetValue(arrayPrev[n])
i.e b[n] === a[n] e.g b[5] === a[5]
Meaning all Elements should be grouped by type, and in this sorted by value.
Where any call to a Function F in C shall be at least implemented before ES5, such that compatibility is given without the need of any shim.
My current approach is to Mark the Objects in arrayPrev to sort them accordingly in arrayCurr and later delete the Marker again. But that seems rather not that efficient.
Heres the current sort function used.
function sort3 (curr,prev) {
var weight = {
"[object Undefined]":6,
"[object Object]":5,
"[object Null]":4,
"[object String]":3,
"[object Number]":2,
"[object Boolean]":1
}
if (prev) { //mark the objects
for (var i = prev.length,j,t;i>0;i--) {
t = typeof (j = prev[i]);
if (j != null && t === "object") {
j._pos = i;
} else if (t !== "object" && t != "undefined" ) break;
}
}
curr.sort (sorter);
if (prev) {
for (var k = prev.length,l,t;k>0;k--) {
t = typeof (l = prev[k]);
if (t === "object" && l != null) {
delete l._pos;
} else if (t !== "object" && t != "undefined" ) break;
}
}
return curr;
function sorter (a,b) {
var tStr = Object.prototype.toString
var types = [tStr.call(a),tStr.call(b)]
var ret = [0,0];
if (types[0] === types[1] && types[0] === "[object Object]") {
if (prev) return a._pos - b._pos
else {
return a === b ? 0 : 1;
}
} else if (types [0] !== types [1]){
return weight[types[0]] - weight[types[1]]
}
return a>b?1:a<b?-1:0;
}
}
Heres a Fiddle as well as a JSPerf (feel free to add your snippet)
And the old Fiddle
If you know the arrays contain the same elements (with the same number of repetitions, possibly in a different order), then you can just copy the old array into the new one, like so:
function strangeSort(curr, prev) {
curr.length = 0; // delete the contents of curr
curr.push.apply(curr, prev); // append the contents of prev to curr
}
If you don't know the arrays contain the same elements, it doesn't make sense to do what you're asking.
Judging by the thing you linked, it's likely that you're trying to determine whether the arrays contain the same elements. In that case, the question you're asking isn't the question you mean to ask, and a sort-based approach may not be what you want at all. Instead, I recommend a count-based algorithm.
Compare the lengths of the arrays. If they're different, the arrays do not contain the same elements; return false. If the lengths are equal, continue.
Iterate through the first array and associate each element with a count of how many times you've seen it. Now that ES6 Maps exist, a Map is probably the best way to track the counts. If you don't use a Map, it may be necessary or convenient to maintain counts for items of different data types differently. (If you maintain counts for objects by giving them a new property, delete the new properties before you return.)
Iterate through the second array. For each element,
If no count is recorded for the element, return false.
If the count for the element is positive, decrease it by 1.
If the count for the element is 0, the element appears more times in the second array than in the first. Return false.
Return true.
If step 4 is reached, every item appears at least as many times in the first array as it does in the second. Otherwise, it would have been detected in step 3.1 or 3.3. If any item appeared more times in the first array than in the second, the first array would be bigger, and the algorithm would have returned in step 1. Thus, the arrays must contain the same elements with the same number of repetitions.
from the description, it appears you can simply use a sort function:
function sortOb(a,b){a=JSON.stringify(a);b=JSON.stringify(b); return a===b?0:(a>b?1:-1);}
var x = {a:1};
var y = {a:2};
var a = [1,x,2,3,y,4,x]
var b = [1,y,3,4,x,x,2]
a.sort(sortOb);
b.sort(sortOb);
console.log (a,b);
Your function always returns a copy of sort.el, but you can have that easier:
var sort = (function () {
var tmp;
function sorter(a, b) {
var types = [typeof a, typeof b];
if (types[0] === "object" && types[1] === "object") {
return tmp.indexOf(a) - tmp.indexOf(b); // sort by position in original
}
if (types[0] == "object") {
return 1;
}
if (types[1] == "object") {
return -1;
}
return a > b ? 1 : a < b ? -1 : 0;
}
return function (el) {
if (tmp) {
for (var i = 0; i < el.length; i++) {
el[i] = tmp[i]; // edit el in-place, same order as tmp
}
return el;
}
tmp = [].slice.call(el); // copy original
return tmp = el.sort(sorter); // cache result
};
})();
Note that I replaced sort.el by tmp and a closure. Fiddle: http://jsfiddle.net/VLSKK/
Edit: This (as well as your original solution)
only works when the arrays contain the same elements.
maintains the order of different objects in a
but
does not mess up when called more than twice
Try this
function ComplexSort (a, b)
{
if(typeof a == "object") {
a = a.a;
}
if(typeof b == "object") {
b = b.a;
}
return a-b;
}
var x = {a:1};
var y = {a:2};
var a = [1,x,2,3,y,4,x]
var b = [1,y,3,4,x,x,2]
a.sort(ComplexSort);
b.sort(ComplexSort);
console.log ("Consistent", a,b);

Categories