Array's elements in JavaScript [duplicate] - javascript

This question already has answers here:
Get the element with the highest occurrence in an array
(42 answers)
Counting the occurrences / frequency of array elements
(39 answers)
Closed 28 days ago.
What am I trying to do:
Given an array of numbers, for example: ["1", "2", "1", "1", "2", "2", "3"],
I want to find the element that is most repeated in the array.
But, I also want to know if there is more than 1 element that satisfies the requirement, and what are those elements.
I couldn't think of any idea on how to start with this yet...

This is an approach using Array.reduce()
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce
First I determine for each unique value in the array how many times it does occur, by returning an object like {"1": 3, "2": 3, "3": 1}
Then I determine which are the values occurred most of the times
in the array, by returning an object like {"count": 3, "values": ["1", "2"]}
const data = ["1", "2", "1", "1", "2", "2", "3"];
//returns the number of time each unique value occurs in the array
const counts = data.reduce( (counts, item) => {
if(item in counts)
counts[item] += 1;
else
counts[item] = 1;
return counts;
}, {});
console.log(counts);
/*
{
"1": 3,
"2": 3,
"3": 1
}
*/
//returns which values and how many times occur the most
const max = Object.entries(counts)
.reduce((max, [value, count])=> {
if(count < max.count)
return max;
if(count == max.count){
max.values.push(value);
return max;
}
return {count: count, values: [value]};
},{count: 0, values: []});
console.log(max);
/*
{
"count": 3,
"values": [
"1",
"2"
]
}
*/

Related

How to create an object containing a range of values for a key

I'm trying to create an object that should hold a range of values for a key which I would use as a look-up table. For example, it needs to "catch" values in the ranges: 500-524, 600-650, etc..
e.g.:
const numbers = {
500 to 524: "20",
600 to 650: "25"
}
And I would like to access the value in the following way:
user.list.map(list => numbers[user.points]).
I know I can put all the values from the range as keys but that would be highly inefficient:
const numbers = {
"500": "20",
"501": "20",
"502": "20",
"503": "20",
(...)
}
So, is it possible to include ranges somehow?
You could set it up like this:
numbers = [
{"start": 500, "end": 524, "value": "20"},
...
...
]
function getFromNumbers(num) {
for(let i=0; i<numbers.length; i++) {
numVal = numbers[i];
if(numVal.start <= num && numVal.end >= num)
return numVal.value;
}
}
console.log(user.list.map(list => getFromNumbers(user.points)))
Why don't you create an object like this:
const numbers =
[
{
start : 500
end : 524
value :20
},
{
start : 600
end : 650
value : 25
}
]
I think you should inverse the solution. You can create object, where key is "20" and value is array of values. For example:
const numbers = {
"20": _.range(500, 524)
}

How do I verify and count the presence of specific data in an associative array?

I have a question about manipulating data in an associative array.
What I want to do
I want to verify if an order exists in sellingItems.
Background(why?)
I want to check if there is an order to return the number of products in stock as a response.
Question
I want to check if a specific data (order) exists in an associative array and calculate the inventory count.
public calculateStockQuantity(itemInstances) {
const stockQuantity = //We want to count the number of items in stock. In this case, we want it to be 2 (calculated based on whether the data exists in sellingItem.order or not).)
  return stockQuantity;
}
Associative array of targets
//There are three itemInstances for one product because the number of products sold is three.
itemInstances =
[
{
"id": "1",
"sellingItem": [
{
"id": 1,
"price": 3000,
"orderedItem": [
{
"id": 1
              "ordered_at": "2021-04-01 10:00:00"
}
]
}
]
},
{
"id": "2",
"sellingItem": [
{
"id": 2,
"price": 3000,
"orderedItem": []
}
]
},
{
"id": "2",
"sellingItem": [
{
"id": 2,
"price": 3000,
"orderedItem": []
}
]
}
]
Sorry for asking like a newbie.
Please check if this is something you are looking for, assuming if orderedItem array is empty then that sellingItem will be counted as in stock
let count = itemInstances.filter(({sellingItem : [{ orderedItem }]}) => orderedItem.length === 0).length;
console.log(count); //return 2 based on question data

Why am I getting a return of index two?

I can not understand why my return is index 2 and not index 0 in the for of loop.
function cardPicker() {
let cards = [
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"10",
"J",
"Q",
"K",
"A"
];
for (p of cards) {
return cards[p];
}
}
The for ... of loop iterates through the values of the array, not the indexes. Your loop therefore returns the value at index 2 in the array, the string "4". If you changed it to a for ... in loop, you'd get the string "2". Of course, there's no point to the loop at all because the only thing the loop does is return, so it will exit on the first iteration.
Also p should be declared with let or var.
p in your example will be "2", so you will return the index 2 of your array, which will returns "4".
Change this:
for (p of cards) {
return cards[p];
}
To this:
for (p in cards) {
return cards[p];
}

Javascript - delete object from JSON array [duplicate]

This question already has answers here:
Find and remove objects in an array based on a key value in JavaScript
(14 answers)
Closed 5 years ago.
I would like to delete an object from a JSON objects array.
Here is the array:
var standardRatingArray = [
{ "Q": "Meal",
"type": "stars"
},
{ "Q": "Drinks",
"type": "stars"
},
{ "Q": "Cleanliness",
"type": "stars"
}
];
For example how can I delete the object whose key is "Q": "Drinks" ?
Preferably of course without iterating the array.
Thanks in advance.
You have to find the index of the item to remove, so you'll always have to iterate the array, at least partially. In ES6, I would do it like this:
const standardRatingArray = [
{ "Q": "Meal",
"type": "stars"
},
{ "Q": "Drinks",
"type": "stars"
},
{ "Q": "Cleanliness",
"type": "stars"
}
];
const index = standardRatingArray.findIndex(x => x.Q === "Drinks");
if (index !== undefined) standardRatingArray.splice(index, 1);
console.log("After removal:", standardRatingArray);

Javascript - how to pick random elements from an array in order?

I have an array
var numbers = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18"];
and trying to get random items from it, so:
console.log(_.sample(numbers, 5));
this will give me 5 random numbers (strings) from the array in a random order, like:
"17", "2", "3", "18", "10"
How do I get a sorted list or random items, like?
"2", "3", "10", "17", "18"
_.sample will probably not be the best choice here. I am trying to get random items from a given array and have these items picked up from left to right of the array.
How to do this in javascritp?
Thank you.
EDIT: I have an array of strings, not numbers, so I cannot sort the randomly picked items.
EDIT2: To avoid confusing, in the array are words (= strings), I used there numbers as strings to more easily demonstrate what I am trying to achieve. (sorry for possible confusions)
You can use Array.prototype.sort to sort the returned array:
ie.
_.sample(numbers, 5).sort(function(a, b) { return parseInt(a, 10) - parseInt(b, 10) })
A better random would be:
var randomChoice = numbers[~~(Math.random() * numbers.length)]
Note: the ~~ performs the same action as Math.floor() in this context. They can be interchanged.
All together:
var numbers = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18"];
var randomSample = []
for(var i=0; i < 5; i++) {
var randomChoice = numbers[~~(Math.random() * numbers.length)]
randomSample.push(randomChoice)
}
var sortedRandomSample = randomSample.sort(function(a, b) { return parseInt(a, 10) - parseInt(b, 10) })
Demo: https://jsbin.com/zosizefaga/edit?html,js,console,output
Here is a solution that doesn't make any assumption about the original order. The idea is to lookup the element's position in the original array and sort by that. However, that assumes that every element is unique.
sample.sort(function(a, b) {
return numbers.indexOf(a) - numbers.indexOf(b);
});
This will also be quite slow for large arrays.
Why don't you implement your own method of sample and after calling _.sample you call the method sort?
The easiest method I can think of is as follows:
var randomSample = _.sample(numbers.map(function(v,i){ return i; }), 5)
.sort(function(a,b){ return a-b; })
.map(function(v){ return numbers[v]; });
That is, make a temporary array that holds the indices of the original array, i.e., just the numbers 0 through numbers.length - 1):
var indices = numbers.map(function(v,i){ return i; })
Take a random sample from that array:
var sampleIndices = _.sample(indices, 5)
Sort the sample:
sampleIndices.sort(function(a,b){ return a-b; })
Then use the sorted, randomly selected indices to get values out of the original array:
var randomSample = sampleIndices.map(function(v){ return numbers[v]; });
And as shown at the beginning of my answer, you can do it all in one line without using the indices and sampleIndices variables. Although if you are going to be regularly taking samples from the same numbers array it would probably make sense to keep the indices variable to save rebuilding it every time, especially if the original array is quite large.
This will work regardless of what type of values are in the original array, because those values are just selected out at the end once random indices have been selected.
Try this:
function random(array, elements) {
return array.concat().sort(function() {
if (Math.random() < 0.5) {
return -1;
} else {
return 1;
}
}).slice(0, elements).sort(
function(a, b) {
return a - b
});
}
Here's the fiddle:
JSFiddle
This is a proposal without sorting and uses an helper array random for the selected items.
First get an empty array, then fill with true until count elements are filled and the filter the original array with the random selected positions.
This solution works for any content of the given array, without sort or lookup with indexOf.
function getSortedRandom(array, count) {
var random = array.map(function () { return false; }),
r;
while (count) {
r = Math.floor(Math.random() * array.length);
if (!random[r]) {
random[r] = true;
count--;
}
}
return array.filter(function (_, i) {
return random[i];
});
}
var random = getSortedRandom(["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18"], 5);
document.write('<pre>' + JSON.stringify(random, 0, 4) + '</pre>');
As of lodash 4.0.0, you can use the _.sampleSize function in conjunction with sort:
var numbers = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18"];
var randomSample = _.sampleSize(numbers, 5).sort();
console.log(randomSample);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.14.1/lodash.min.js"></script>

Categories