indexOf not working correctly in javaScript [duplicate] - javascript

This question already has answers here:
Difference Between indexOf and findIndex function of array
(9 answers)
Closed 4 months ago.
my code is :
[{a:1},{b:2},{c:3}].indexOf(obj=>{return obj.a ==1})
I expect return 0 but result is -1
what is the problem?

The main difference are the parameters of these functions:
Array.prototype.indexOf() expects a value as first parameter. This
makes it a good choice to find the index in arrays of primitive types
(like string, number, or boolean).
Array.prototype.findIndex() expects a callback as first parameter.
Use this if you need the index in arrays with non-primitive types
(e.g. objects) or your find condition is more complex than just a
value.
This question is similar to this and the answer can also be found there.

Related

Pass to method object values as arguments [duplicate]

This question already has answers here:
Passing an array as a function parameter in JavaScript
(12 answers)
Closed 2 years ago.
I have next code:
someFunct(Object.values(Obj));
What I need is to pass object values in to 'someFunct' as separate argument, not as array.
You can use the spreading operator to spread the values:
someFunct(...Object.values(Obj));
You should use spread operator ...
someFunct(...Object.values(Obj));
Note: This method may cause some problems in code because Object.values() is not guaranteed to have same order. The better option is to pass and object and then destructure it.

Any good reasons to use the Number constructor (as opposed to literals)? [duplicate]

This question already has answers here:
What is the difference between JavaScript object and primitive types?
(1 answer)
Why to avoid creating objects of primitives in JavaScript?
(4 answers)
JavaScript primitive types and corresponding objects
(2 answers)
Closed 2 years ago.
The community reviewed whether to reopen this question 1 year ago and left it closed:
Duplicate This question has been answered, is not unique, and doesn’t differentiate itself from another question.
Are there any good reasons to use new Number(n)? Why does this constructor exist?
I can think of several reasons to avoid it, eg.,
literals are more memory efficient since they don't construct anything new.
literals are equal to each other (5 === 5 but new Number(5) !== new Number(5)).
the typeof operator indicates that it's a number rather than an object.
new Number(0) is never falsey. (!!new Number(false) == true).
You can use it for type conversion, but there are more concise methods. (+false === 0).
To be clear, I understand the Number object has useful methods and properties, my question is specifically about the constructor.
I'm using Number as an example, but I don't understand why Javascript exposes other constructors where literals are available either (String, Object, Array, etc.).
Why do these exist and are there ever any good reason to use them?

In operator returns false [duplicate]

This question already has answers here:
javascript string in list returns false
(3 answers)
Closed 3 years ago.
Why this statement returns false? It's really weird
console.log("100038916831294" in ["100003748210938", "100038916831294"]);
The in operator tells you whether a value exists as a property name in an object. The property names of your array are "0" and "1".
You can use one of the Array methods to check if a value is in the array, like .indexOf() or .includes():
console.log(["100003748210938", "100038916831294"].includes("100038916831294"));
The in operator in JavaScript compares indexes or property names in arrays instead of the value itself.
For example, if we write console.log(0 in ["abc","pqr"]); it will print true. However, if we use the value, like in console.log("abc" in ["abc","pqr"]); it will print false.
You can further read about it on https://www.w3schools.com/jsref/jsref_operators.asp.

Index of array? [duplicate]

This question already has answers here:
How to compare arrays in JavaScript?
(55 answers)
Why does this index of a two dimensional array return -1 [duplicate]
(2 answers)
Closed 3 years ago.
I have simple nested array, like:
var arr = [[75.0], [65.0]] ;
and when I do:
arr.indexOf( [75.0] );
I expect 0, but I get -1, what gives?
From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf :
indexOf() compares searchElement to elements of the Array using strict equality (the same method used by the === or triple-equals operator).
There is the problem. In your example, you have an array of arrays. Comparing with === operator means that for it to evaluate to true, it has to be the same array object. Clearly it is a different object so it is not found from the array.
You need to use Array.find() instead where you can provide the testing function. See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find

Any way in JavaScript to deep-check an object for a truthy value? [duplicate]

This question already has answers here:
Null-safe property access (and conditional assignment) in ES6/2015
(11 answers)
Closed 6 years ago.
I believe there's a mechanism for this in CoffeeScript (the ? token), but I'm wondering if there's a better way to do this kind of check in ES6:
if (item && item.integrations && item.integrations.slackData) ...
(besides writing a helper function, which is the immediately obvious solution)
EDIT: The goal here is to make the code is simple and terse as possible.
Example object:
item = { integrations: { slackData: { url: '...' } } };
EDIT 2: Thanks for pointing out the duplicates. I couldn't figure out what terms to search for. I'm probably going to go with using lodash's _.get() function.
You can use Array.prototype.every()
var check = [item, item.integrations, item.integrations.slackData]
.every(function(element) { return element });
Edit, Updated
As noted at comments by #FelixKling, the pattern at above using .every() will fail if item.integrations is undefined.
Given the example object at Question you can use JSON.stringify(), String.prototype.match() with RegExp /"integrations":|"slackData":|"ur‌​l":/g/, then check that .length of resulting array, if any, is equal to the number of properties expected; in the present case 3.
A javascript object which is passed to JSON.stringify() should have properties with the following pattern:
" followed by property followed by " followed by :. Depending on the source object, the RegExp can be further adjusted to meet the specific properties and values of that object.
JSON.stringify(item).match(/"integrations":|"slackData":|"ur‌​l":/g).length === 3
Note that JSON.stringify() has a replacer option which can be used to match properties of the object. The replacer function option is recursive. See also
remove object from nested array
Nested object and array destructuring
Convert javascript object to array of individual objects
How do I filter Object and get a new Object?
but I'm wondering if there's a better way to do this kind of check in
ES6:
The present Answer does not attempt to indicate that using JSON.stringify() and RegExp to match or filter a javascript object is "better"; but only that the approach can meet the described requirement at the present Question.

Categories

Resources