I am new to object oriented coding. I found this example when practising.
It is confusing; whenever we are passing an array to a function it is removing the duplicates.
I wondered where are the duplicated values,how they are gone and how it is sorting the array?
Can any one explain me in deeply. I am new to object oriented concepts.
function duplicate(arr) {
var i, len = arr.length,
obj = {};
for (i = 0; i < len; i += 1) {
obj[arr[i]] = 0;
}
return obj;
}
//calling function
console.log(
duplicate([1, 2, 3, 4, 4, 3, 2, 1, 0, -1, 10, 100])
);
// result::{0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 10: 0, 100: 0, -1: 0}
This is quite a strange way to do it but I've commented the code to make it easier to understand.
function duplicate(arr) {
// declare variables
var i, len = arr.length,
obj = {};
// for each item in the array
for (i = 0; i < len; i += 1) {
// create or set key within obj named the current array item with the value 0
obj[arr[i]] = 0;
}
// return the created object
return obj;
}
//calling function and passing the array
console.log(duplicate([1, 2, 3, 4, 4, 3, 2, 1, 0, -1, 10, 100]))
This works because when the key is set it is unique so calling again will edit the existing entry and not add another.
A quick way to make this better would be to return just the object keys rather than the whole object. You'd do this by changing return obj; to return Object.keys(obj);
Related
Write a program to find count of the most frequent item of an array. Assume that input is array of integers.
Example:
Input array: [3, -1, -1, -1, 2, 3, -1, 3, -1, 2, 4, 9, 3]
Ouptut: 5
Most frequent number in example array is -1. It occurs 5 times in input array.
Here is my code:
function mostFrequentItemCount(collection) {
var copy = collection.slice(0);
for (var i = 0; i < collection.length; i++) {
var output = 0;
for (var x = 0; x < copy.length; x++) {
if (collection[i] == copy[x]) {
output++;
}
}
}
return output;
}
It seems to be just counting the reoccurrence of the first number in the array not the one that occurs the most. I can't figure out how to make it count the most occurring one.
If i didn't miss anything, and if you really want to find the count of the most frequent item of an array, i guess one approach would be this one:
function existsInCollection(item, collection) {
for(var i = 0; i < collection.length; i++) {
if(collection[i] === item) {
return true;
}
}
return false;
}
function mostFrequentItemCount(collection) {
var most_frequent_count = 0;
var item_count = 0;
var already_checked = [];
for(var i = 0; i < collection.length; i++) {
// if the item was already checked, passes to the next
if(existsInCollection(collection[i], already_checked)) {
continue;
} else {
// if it doesn't, adds to the already_checked list
already_checked.push(collection[i]);
}
for(var j = 0; j < collection.length; j++)
if(collection[j] === collection[i])
item_count++;
if(item_count > most_frequent_count)
most_frequent_count = item_count;
item_count = 0;
}
return most_frequent_count;
}
var items = [3, -1, -1, -1, 2, 3, -1, 3, -1, 2, 4, 9, 3];
alert(mostFrequentItemCount(items));
What happens here is:
On each item ('i' loop), it will run another loop ('j') through all items, and count how many are equal to the [i] item. After this second loop, it will be verified if that item count is greater than the most_frequent_count that we already have, and if it is, updates it.
Since we always use the same variable 'item_count' to check each number count, after the verification of each number we reset it to 0.
This may not be the best answer, but it was what occurred me at the moment.
EDIT:
I added a function to check if an item already exists in a list, to avoid the loop from check the same item again.
The problem is that you override the output variable each loop iteration, so after the for loop ends your output variable holds occurrences of the last element of input array.
You should use variables like var best_element = collection[0] and var best_element_count = -1 (initialized like this). After each inner loop you check if algo found any better solution (best_element_count < output) and update best_element.
Edit: following #Alnitak comment you should also reset the output variable after each inner loop iteration.
First you will need to construct a collection (or object) that contains the element and the count of occurances. Second you will need to iterate the result to find the key that has the highest value.
JSFiddle
function mostFrequentItemCount(collection) {
var output = {};
for (var i = 0; i < collection.length; i++) {
var item = collection[i];
if (!(item in output))
output[item] = 0;
output[item]++;
}
var result = [0, 5e-324];
for (var item in output) {
if (output[item] > result[1]) {
result[0] = parseFloat(item);
result[1] = output[item];
}
}
return result;
}
var input = [3, -1, -1, -1, 2, 3, -1, 3, -1, 2, 4, 9, 3];
var result = mostFrequentItemCount(input);
console.log(result);
The snippet above simply creates a new object (output) which contains a property for each of the unique elements in the array. The result is something like.
2:2
3:4
4:1
9:1
-1:5
So now we have an object with the property for the number and the value for the occurances. Next we then interate through each of the properties in the output for(var item in output) and determine which value is the greatest.
Now this returns an array with the value at index 0 being the number and the value at index 1 being the count of the element.
Check this solution.
var store = [3, -1, -1, -1, 2, 3, -1, 3, -1, 2, 4, 9, 3];
var frequency = {}; // array of frequency.
var max = 0; // holds the max frequency.
var result; // holds the max frequency element.
for(var v in store) {
frequency[store[v]]=(frequency[store[v]] || 0)+1; // increment frequency.
if(frequency[store[v]] > max) { // is this frequency > max so far ?
max = frequency[store[v]]; // update max.
result = store[v]; // update result.
}
}
alert(max);
So this update to your method will return an object with each key and the count for that key in the array. How you format an output to say what key has what count is up to you.
Edit: Updated to include the complete solution to the problem.
function mostFrequentItemCount(collection) {
var copy = collection.slice(0);
var results = {};
for (var i = 0; i < collection.length; i++) {
var count = 0;
for (var x = 0; x < copy.length; x++) {
if (collection[i] == copy[x]) {
count++;
}
}
results[collection[i]] = count;
}
return results;
}
var inputArray = [3, -1, -1, -1, 2, 3, -1, 3, -1, 2, 4, 9, 3];
var occurances = mostFrequentItemCount(inputArray);
var keyWithHighestOccurance = Object.keys(occurances).reduce(function(a, b){ return occurances[a] > occurances[b] ? a : b });
var highestOccurance = occurances[keyWithHighestOccurance];
console.log("Most frequent number in example array is " + keyWithHighestOccurance + ". It occurs " + highestOccurance + " times in the input array.");
I am needing to find the correct way to have javascript loop through an array, find all numbers that are divisible by 3, and push those numbers into a new array.
Here is what I have so far..
var array = [],
threes = [];
function loveTheThrees(array) {
for (i = 0, len = array.length; i < len; i++) {
threes = array.push(i % 3);
}
return threes;
}
So if we pass through an array of [1, 2, 3, 4, 5, 6] through the function, it would push out the numbers 3 and 6 into the "threes" array. Hopefully this makes sense.
You can use Array#filter for this task.
filter() calls a provided callback function once for each element in an array, and constructs a new array of all the values for which callback returns a true value or a value that coerces to true. callback is invoked only for indexes of the array which have assigned values; it is not invoked for indexes which have been deleted or which have never been assigned values. Array elements which do not pass the callback test are simply skipped, and are not included in the new array.
function loveTheThrees(array) {
return array.filter(function (a) {
return !(a % 3);
});
}
document.write('<pre>' + JSON.stringify(loveTheThrees([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]), 0, 4) + '</pre>');
console.log([1, 2, 3, 4, 5, 6, 7].filter(function(a){return a%3===0;}));
Array.filter() iterates over array and move current object to another array if callback returns true. In this case I have written a callback which returns true if it is divisible by three so only those items will be added to different array
var array = [],
three = [];
function loveTheThrees(array) {
for (i = 0, len = array.length; i < len; i++) {
if(array[i] % 3 == 0){
three.push(array[i]);
}
}
return three;
}
Using Filter like suggested by Nina is defiantly the better way to do this. However Im assuming you are a beginner and may not understand callbacks yet, In this case this function will work:
function loveTheThrees(collection){
var newArray = []
for (var i =0; i< collection.length;i++){
if (myArray[i] % 3 === 0){
newArray.push(collection[i])
}
}
return newArray;
}
loveTheThrees=(arr)=>arr.filter(el=>Boolean(parseFloat(el)) && isFinite(el) && !Boolean(el%3))
es6 version + skipping non numbers
loveTheThrees([null,undefined,'haha',100,3,6])
Result: [3,6]
Check if the number is divisible by 3 if so then add it to array. Try this
function loveTheThrees(array) {
for (i = 0, len = array.length; i < len; i++) {
if(array[i] % 3 == 0){
three.push(array[I]);
}
}
var originalArray = [1, 2, 3, 4, 5, 6, 7, 8, 9];
function loveTheThrees(array1) {
var threes = [];
for (var i = 0; i < array1.length; i++) {
if (array1[i] % 3 === 0) {
threes.push(array1[i]);
}
}
return threes;
}
loveTheThrees(originalArray);
In ES6:
const arr = [1, 33, 54, 30, 11, 203, 323, 100, 9];
// This single line function allow you to do it:
const isDivisibleBy3 = arr => arr.filter(val => val % 3 == 0);
console.log(isDivisibleBy3(arr));
// The console output is [ 33, 54, 30, 9 ]
I am looping through an object and then upon each object I am comparing it to the items in my array in hopes to then push the objects that are not the same into my ItemsNotInObject array. Hopefully someone can shine some light on this for me. Thank you in advance.
var obj = {a:1, a:2, a:3};
var array = [1, 4, 2, 5, 6];
var ItemsNotInObject = [];
for (var prop in obj) {
for(var i = 0, al = array.length; i < al; i++){
if( obj[prop].a !== array[i] ){
ItemsNotInObject.push(array[i]);
}
}
}
console.log(ItemsNotInObject);
//output of array: 1 , 4 , 2 , 5, 6
//output desired is: 4 , 5 , 6
Your object has duplicate keys. This is not a valid JSON object. Make them unique
Do not access the object value like obj[prop].a, obj[prop] is a
Clone the original array.
Use indexOf() to check if the array contains the object property or not.
If it does, remove it from the cloned array.
var obj = {
a: 1,
b: 2,
c: 3
};
var array = [1, 4, 2, 5, 6];
var ItemsNotInObject = array.slice(); //clone the array
for (var prop in obj) {
if (array.indexOf(obj[prop]) != -1) {
for (var i = 0; i < ItemsNotInObject.length; i++) {
if (ItemsNotInObject[i] == obj[prop]) {
ItemsNotInObject.splice(i, 1); //now simply remove it because it exists
}
}
}
}
console.log(ItemsNotInObject);
If you can make your obj variable an array, you can do it this way;
var obj = [1, 2, 3];
var array = [1, 4, 2, 5, 6];
var ItemsNotInObject = [];
for(i in array){
if( obj.indexOf(array[i]) < 0) ItemsNotInObject.push(array[i]);
}
console.log(ItemsNotInObject);
if the obj variable needs to be json object please provide the proper form of it so i can change the code according to that.
I have an array of 5 elements ex. arr = [1,2,3,4,5]; I want to add elements between these elements, and place them in new array arr1 = [1,0,0,0,2,0,0,0,3,0,0,0,4,0,0,0,5,0,0,0];. When i alert arr1 i get the same array as it is, but when i alert arr1.length i get that it`s length is 5, when it is actually 20. Can you help me fix this, or tell me why do i get that result. Here is an example of the code i am using:
function niza(val,times){
var arr = [];
for (var i=0;i<times;i++) {
arr.push(val);
}
return arr;
}
and then this:
var y1=0;
var arr= [];
var a = new Array();
for (var j=0;j<Niza1.length;j++) {
y1 = Niza1[j];
arr = y1 + "," + niza(0,11);
a.push(arr);
}
where Niza1 holds the 5 elements mentioned before in arr, and a holds the elements mentioned in arr1.
I'm not sure to understand the code you wrote, but do you know you can add multiple elements at once with arr.push ?
var array1 = [1, 2, 3, 4, 5];
var array2 = [];
for(var i = 0 ; i < array1.length ; i++) {
array2.push(array1[i], 0, 0, 0);
}
//array2 == [1, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0, 4, 0, 0, 0, 5, 0, 0, 0]
You question is a little hard to follow, but try something like this:
function inject(original, val, times) {
var res = [];
for(var i=0; i < original.length; i++){
res.push(original[i]);
for(var j = 0; j < times; j++){
res.push(val);
}
}
return res;
}
Demonstration
Here's a solution that would work with an arbitrary list and length, and is therefore reusable:
function inject(original, values) {
var result = [];
for (var i = 0 ; i < original.length ; i++) {
result.push(original[i]);
result.push.apply(result, values);
}
return result;
}
console.log(inject([1,2,3], [0,0,0]));
// output: [1, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0]
console.log(inject([1,1,1], [2,6,2,6]));
// output: [1, 2, 6, 2, 6, 1, 2, 6, 2, 6, 1, 2, 6, 2, 6]
It leverages the the native apply (here's an explanation) function to execute the push with an arbitrary list of arguments, defined by the values array.
I'm using javascript, and I have an array containing multiple values, which may be non-unique. I'd like to take this array and generate a new array, or ordered list, of its keys in ascending order of value. For example, if I have [ 2, 2, 4, 5, 1, 6 ], I'd like to generate [ 5, 4, 0, 1, 2, 3 ].
I was thinking of iterating over the original list and inserting each value into the new list while checking for proper placement by comparing to the existing values of the new list every time an insertion is performed. This seems wasteful, though, as I'd have to (potentially) check every value of the new list for every insertion.
Anyone have a simpler method for this?
I think you meant [ 4, 0, 1, 2, 3, 5 ].
function GetSortedKeys(values) {
var array_with_keys = [];
for (var i = 0; i < values.length; i++) {
array_with_keys.push({ key: i, value: values[i] });
}
array_with_keys.sort(function(a, b) {
if (a.value < b.value) { return -1; }
if (a.value > b.value) { return 1; }
return 0;
});
var keys = [];
for (var i = 0; i < array_with_keys.length; i++) {
keys.push(array_with_keys[i].key);
}
return keys;
}
var array = [2, 2, 4, 5, 1, 6];
alert(GetSortedKeys(array));
This is the simplest method I can come up with on Javascript, unfortunately.
Using the nice Underscore.JS:
var get_sorted_keys = function(values) {
var keys_idx = [], i;
for (i = 0; i < values.length; i++) {
keys_idx.push(i);
}
var keys = _.sortBy(keys_idx, function(idx){ return values[idx]; });
return keys;
};
var array = [2, 2, 4, 5, 1, 6];
console.log("Sorted keys:", get_sorted_keys(array));
Output:
Sorted keys: [4, 0, 1, 2, 3, 5]