IndexOf array with strings as index [closed] - javascript

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Probably ill advised, but I have an array with strings for indexes. Now I need to use indexOf and it doesn't work. The code below returns -1. Any way to get b out of this without rewriting everything?
x = [];
x['a'] = 0;
x['b'] = 1;
print(x.indexOf(1));

The fundamental issue you are not understanding is that an Array cannot have strings as indexes. The syntax you are using is an alternate way of defining properties on to an object. All the previous suggestions people are giving you is probably confusing you more. Keep it simple. Arrays have number indexes.
// this is adding values to an array
var x = [];
x[0] = 'one';
x[1] = 'two';
console.log(x[0]); // outputs 'one'
// this is adding a property to an object
var y = {};
y['width'] = 20;
y['height'] = 40;
console.log(y['width']); // outputs 20
console.log(y.height); // outputs 40
// this is adding a property to our previous array
// (because Arrays are objects too in JavaScript)
x['name'] = 'My Array';
console.log(x.name); // outputs 'My Array'
x.indexOf('My Array'); // returns -1 because 'My Array' is not stored in the array
x.indexOf('two'); // returns 1 because that's the index of 'two' in the array

x = [];
x['a'] = 0;
x['b'] = 1;
var valueIndex = Object.keys(x).map(function(prop){
return x[prop]
}).indexOf(1);
Object.keys(x)[valueIndex] //b
Unless it's really going to be in that order just do
Object.keys(x)[1]; //b

Concrete code for the suggestion I made in comments, depending on the scenario this is easier or harder to implement in existing code than for (prop in x):
function put(arr, letter, value) {
arr[letter.toLowerCase().charCodeAt(0)-96] = value;
}
function find(arr, value) {
return String.fromCharCode(x.indexOf(value)+96);
}
x = [];
put(x, 'a', 0);
put(x, 'b', 1);
print(find(x, 1)); // gives b

Related

How to count and add only duplicate value in an array in javascript [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I have an array with some duplicates value. i want to count only duplicate values like
array1 = [1,2,3,4,5,4,1];
and the expected output is = 2
A concise variant if you need a count of all duplicate elements. May be faster than looping with duplicate check:
const array = [1,2,3,4,5,4,1];
const dupCount = array.length - new Set(array).size;
console.log(dupCount);
The easiest way to do this is to make a set that has property names that refer to your values:
const array1 = [1, 2, 3, 4, 5, 4, 1];
const duplicatesSet = array1.reduce((set, value, index) => {
// if an entry has an index nearer the end of the list,
// we know it is a duplicate
if (array1.lastIndexOf(value) !== index)
set.add(value);
return set;
}, new Set());
console.log("Duplicates Set:", [...duplicatesSet.values()]); // show the set
console.log("Duplicates count:", duplicatesSet.size); // output set size
You can use the below code
function countDuplicate(array){ // array to check
array.sort();// sort it so that if value is duplicated it is presented right to it
var count = 0;
for(let i =0; i<array.length; i++){
let j = i+1;
while( j< array.length && array[j] == array[i]){// iterate all same value
j++;
}
if(j-i>1){ //if you have atleast one same value increase the count
count++;
}
i = j -1;// here we are subtracting one because one is increment by for loop
}
return count;}
You can filter the array by ones that match but don't have the same index as the current item. That'll make a new array and you can just output the length of that?
const arr = [1,2,3,4,5,4,1]
const duplicates = arr.filter((item, i) => i !== arr.indexOf(item))
const count = duplicates.length
console.log(duplicates) // Output: [ 4, 1 ]
console.log(count) // Output: 2
It can be a one-liner like
arr.filter((item, i) => i !== arr.indexOf(item)).length

How to print only evens from an array? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I am currently learning to code. I have to create an array and then create a function that prints only the even numbers from the array. Here is what I currently have. I am at a loss on what to do. I am learning from Code Highschool. It is what my class is making us use.
Instructions from codehs:
Write a function called
function onlyEvens(arr)
That takes an array and returns an array with only the even numbers in the original array.
Then, you should print out the new list.
How do I get the code to only print the even numbers that are in the array?
function start(){
var arr = [1,2,3,4,5,6];
var evens = onlyEvens(arr);
println(evens);
}
function onlyEvens(arr){
}
Simply you can use like this
start();
function start(){
var arr = [1,2,3,4,5,6];
var evens = onlyEvens(arr);
console.log(evens);
}
function onlyEvens(arr){
evenArr={};
for (var i = 0,j=0 ;i < arr.length; i++) {
if(arr[i] % 2 === 0) { //
evenArr[j] = arr[i];
j++;
}
}
return evenArr;
}
https://jsfiddle.net/n3jke25n/
The operator you're looking for is the modulus operator.
For any integer variable x, if x % 2 == 1, x is odd. On the other hand, if x % 2 == 0, x is even.
Thus, write an if statement that determines, using the modulus operator, whether the number in question is even; then, if it is, add it to the destination array.
Try using a modulo in onlyEvens whilst cycling the array
for (var i=0;i<arr.length;i++) {
if i%2==0 {
console.log("is even:"+arr[i])
}
}
Something like that, more here: https://en.wikipedia.org/wiki/Modulo_operation

How to remove items from array who's got the same values [duplicate]

This question already has answers here:
How to remove all duplicates from an array of objects?
(77 answers)
Closed 7 years ago.
I am making some checking between array. It is in NodeJS.
The question is:
I have an array:
var items = [];
than I insert some values into it:
items[0] = {a:1, b:222};
items[1] = {a:1, b:333};
items[2] = {a:1, b:222};
items[3] = {a:1, b:4444};
items[4] = {a:1, b:222};
So, what I need to do is: to go threw all array and remove item's that has the same 'b' value.
Example:
After filtering, it should look like:
items[0] = {a:1, b:222};
items[1] = {a:1, b:333};
items[2] = {a:1, b:4444};
As you see elements with indexes 2 and 4 gone, because they has the same b value as element at index 0.
How can I write this little code in JavaScript?
You're looking for an Array.prototype.filter function:
var bValues = {};
items = items
.filter(function(item) {
return bValues[item.b] === undefined && (bValues[item.b] = true);
});
This works by checking if we have seen a particular bValue, and returning false if we have. If we haven't, we set that value on the bValues map and return true.
Edit: I like the nifty suggestion of #dandavis, using the this binding parameter to reduce variable names:
items = items
.filter(function(item) {
return this[item.b] === undefined && (this[item.b] = true);
}, {});
If I understand your question correctly, you want to do a pass to remove every single duplicate b value. This is actually more of an algorithm question than a Javascript question. There are lot of ways to do this, but my answer is going to focus on performance.
Here is one of the faster ways to do this in Javascript (O(n)):
var items = [];
// Insert a bunch of items with signature {a: Number, b: Number}
items = removeDuplicatesOfB(items);
function removeDuplicatesOfB(items) {
var map = {};
var filtered = [];
items.forEach(function (item) {
if (!map[item.b]) {
filtered.push(item);
map[item.b] = true;
}
});
return filtered;
}
At this point you could focus on abstracting out the duplicate removal to make this a reusable function.
All the answers propose roughly equivalent algorithms, so it boils down to what is most understandable. Here's one idea. We'll start off by describing the algorithm in English:
Of all the items, keep those with the first b.
For an item, "first b" means the index of this item is equal to the index of the first element whose b property is equal to the b property of the item.
Now we can pretty much transform that English into JavaScript.
function removeDuplicatesOfB(items) {
// Is this item the first in the array with its b property?
function firstB(item, idx) {
return idx // The index of this item
=== // equal to
items.findIndex( // the index of the first
e => // element
e.b // whose b property
=== // is equal to
item.b // the b property of the item.
)
;
}
return items . // Of all the items,
filter( // keep those with
firstB // the first b.
)
;
}
Or, in non-commented form:
function removeDuplicatesOfB(items) {
function firstB(item, idx) {
return idx === items.findIndex(e => e.b === item.b);
}
return items.filter(firstB);
}
Underscore
Underscore's _.uniq can do this in its sleep, by passing it a "predicate" telling it how to compare the objects for purposes of determining whether they are the "same":
_.uniq(items, function(item) { return item.b; })

pick random value from associated array using javascript? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicates:
JavaScript: Getting random value from an array
How can I choose an object key at random?
suppose we have an array like this:
var MrArray = new Array(5);
MrArray['one']='oneValue';
MrArray['two']='twoValue';
MrArray['three']='threeValue';
MrArray['four']='fourValue';
MrArray['five']='fiveValue';
ok?
the Array is associated.
and we have string key and string value.
now! how can i pick a random value from that?
Edit:i want to use like this:
Array Key Here
Regards
Sam
Using the method described here we can create the following function:
function randomKey(obj) {
var ret;
var c = 0;
for (var key in obj)
if (Math.random() < 1/++c)
ret = key;
return ret;
}
It returns a random key, so to get a random value from MrArray, do this:
var value = MrArray[randomKey(MrArray)];
jsPerf benchmark comparing the speed of this and the other answer.
Here:
function fetch_random(obj) {
var temp_key, keys = [];
for(temp_key in obj) {
if(obj.hasOwnProperty(temp_key)) {
keys.push(temp_key);
}
}
return obj[keys[Math.floor(Math.random() * keys.length)]];
}
Src: How can I choose an object key at random?

Checking length of dictionary object [duplicate]

This question already has answers here:
Length of a JavaScript object
(43 answers)
Closed 3 years ago.
I'm trying to check the length here. Tried count. Is there something I'm missing?
var dNames = {};
dNames = GetAllNames();
for (var i = 0, l = dName.length; i < l; i++)
{
alert("Name: " + dName[i].name);
}
dNames holds name/value pairs. I know that dNames has values in that object but it's still completely skipping over that and when I alert out even dName.length obviously that's not how to do this...so not sure. Looked it up on the web. Could not find anything on this.
What I do is use Object.keys() to return a list of all the keys and then get the length of that
Object.keys(dictionary).length
var c = {'a':'A', 'b':'B', 'c':'C'};
var count = 0;
for (var i in c) {
if (c.hasOwnProperty(i)) count++;
}
alert(count);
This question is confusing. A regular object, {} doesn't have a length property unless you're intending to make your own function constructor which generates custom objects which do have it ( in which case you didn't specify ).
Meaning, you have to get the "length" by a for..in statement on the object, since length is not set, and increment a counter.
I'm confused as to why you need the length. Are you manually setting 0 on the object, or are you relying on custom string keys? eg obj['foo'] = 'bar';. If the latter, again, why the need for length?
Edit #1: Why can't you just do this?
list = [ {name:'john'}, {name:'bob'} ];
Then iterate over list? The length is already set.
Count and show keys in a dictionary (run in console):
o=[];count=0; for (i in topicNames) { ++count; o.push(count+": "+ i) } o.join("\n")
Sample output:
"1: Phase-out Left-hand
2: Define All Top Level Taxonomies But Processes
3: 987
4: 16:00
5: Identify suppliers"
Simple count function:
function size_dict(d){c=0; for (i in d) ++c; return c}

Categories

Resources