This question already has answers here:
Get the element with the highest occurrence in an array
(42 answers)
Closed 3 years ago.
I need to create a very, very lean ES6 arrow function that consoles out the most frequent name in my array....
function mostFrequent(arr){
};
// Example usage
let names = ['Jack', 'Anthony', 'Richy', 'Jane', 'Karen', 'Jane', 'Mary', 'Jane' ];
console.log('The most frequently used name is', mostFrequent(names));
ES6 function to find the most frequent item in an array:
let names = ['Jack', 'Anthony', 'Richy', 'Jane', 'Karen', 'Jane', 'Mary', 'Jane'];
function mostFrequent(arr) {
return arr.sort((x, y) =>
arr.filter(e => e === x).length -
arr.filter(e => e === y).length
).pop();
}
console.log(`The most frequently used name is '${mostFrequent(names)}'`);
Related
I have an array of objects that I get from an API. The property names are dynamic (meaning I don't have an extensive list of all of them). How can I get an array of all distinct objects? The contract specifies that if key is equal value is also equal. I tried to look around but I found nothing quite like this problem.
[ 20:31:28
{
'product-management': 'Product management'
},
{
'product-development': 'Product development'
},
{
'client-work': 'Client work'
},
{
'client-work': 'Client work'
},
{
'product-development': 'Product development'
},
{
'client-work': 'Client work'
},
{
'product-development': 'Product development'
}
]
Spread the array into Object.assign() to merge all objects to a single one. Since all objects properties are unique, this will leave only one key (and value) from the duplicates. Then convert to [key, value] pairs with Object.entries(), and map back to individual objects:
const data = [{"product-management":"Product management"},{"product-development":"Product development"},{"client-work":"Client work"},{"client-work":"Client work"},{"product-development":"Product development"},{"client-work":"Client work"},{"product-development":"Product development"}]
const result = Object.entries(Object.assign({}, ...data))
.map(([k, v]) => ({ [k]: v }))
console.log(result)
Going with #Bergi's suggestion, you can also convert this to a saner API while removing duplicates:
const data = [{"product-management":"Product management"},{"product-development":"Product development"},{"client-work":"Client work"},{"client-work":"Client work"},{"product-development":"Product development"},{"client-work":"Client work"},{"product-development":"Product development"}]
const result = Object.entries(Object.assign({}, ...data))
.map(([key, value]) => ({ key, value }))
console.log(result)
I have some JSON that when converted to an Object it looks like the following:
{
'SOME RANDOM STRING':
{
'Article Headline': 'headline',
'Article Image URL': 'image url',
'Article Published Date': 'date',
'Article URL': 'article url',
'Category': 'mental illness,',
'Location': 'place',
'Source Name': 'source'
}
}
I have it stored in an array called results. How would I be able to access the values within Location as result.location doesn't work.
If its a JSON, you don't have to convert it into an array. You can parse it directly something like below.
var obj = {
'-KzZaDXhWRwdzfKUf5tl':
{ 'Article Headline': 'headline',
'Article Image URL': 'image url',
'Article Published Date': 'date',
'Article URL': 'article url',
'Category': 'mental illness,',
'Location': 'place',
'Source Name': 'source' }
}
console.log(obj['-KzZaDXhWRwdzfKUf5tl'].Location);
The above prints place to the screen.
The path to the Object would be results[0]['RANDOM STRING'].location, however since you don't know the RANDOM STRING then it'd be best to use non referential methods to access the nested object.
Thankfully there are many tools in recent version of NodeJS/Javascript to do just this!
Array.prototype.map(function(item, index, array), context) seems like the function you want! It will create a new array based on the return of the function as applied to each thing in the array.
Then you can change each object by using other tools built onto the object itself like
// array of keys, useful for looking for a specific key
Object.keys(someReallyObtuseObject)
// array of VALUES! Awesome for looking for a specific data type
Object.values(someReallyObtuseObject)
Checking Node Green for Object.values shows it's available in NodeJS 7.10 or greater and for Object.keys shows it is available as far back as 4.8.6!
Don't forget though that these transform the object to an array. After that you can use forEach, filter, map, and many other array methods to access the data!
An Example
Say I have an array from a database called results
const results = [{...},{...},...];
I want to find a result with the identifier I know
// I will either find the result, or receive undefined
let result = results.filter(r => r[key] == identifier)[0];
However in my result the object has a key called "related posts" and it is an object with a key being a unique ID for each related post. I want to access said posts, but I don't know their unique IDs, so I want to convert it to an array to make processing it easier
// This gives me an array of related posts with their ID now nested inside them
let relatedPosts = Object.keys(result['related posts']).map(k => {
let r = result['related posts'][k];
r.id = k;
return r;
});
Now I can go over my related posts easily, and I never had to know the ID of the post. Let's say I want to console.log each post(you would really never want to do this)
relatedPosts.forEach(console.log);
Easy!
Example 2, getting the location from an array of users
Users are defined as an object with keys 'first', 'last', 'location'
const users = [{...},{...},...]
let locations = users.map(user => user.location)
i'm creating an API in Lumen and i need to create a method that will get dates from two colums on the same table and return any years that occur between those dates, returning them all as a single array.
So for instance, imagine a table column named start_date and another named end_date
start_date | end_date getAllYears() should return =>
[1983, 1984, 1985, 1986, 1987,
1999, 2000, 2001, 2002, 2003,
..., 2016]
1999-05-09 | 2002-04-03
1983-03-12 | 1987-09-23
2001-02-12 | 2016-11-27
Currently i have a method that manages to do this on other types of more specific queries, the major problem with this attempt, is that due to the sheer mass of SQL records that i'm retrieving, a method like this causes my request to time out every single time.
MY INEFFICIENT METHOD that makes little use of Lumen/Laravel
public function getAllYears(){
$dates = $this->model->select('data_ini', 'data_fim')->get();
$results = [];
foreach ($dates as $obj){
$carbonBegin = Carbon::createFromDate($obj->data_ini->year);
$carbonEnd = Carbon::createFromDate($obj->data_fim->year);
if($carbonEnd->year === 9999){
$carbonEnd->year = date('Y');
}
$carbonEnd->year++;
// Simple method that runs a DatePeriod method
$dateRange = $this->helper->createDateRange($carbonBegin, $carbonEnd);
$results = array_merge($results, $dateRange);
}
sort($results);
$cleanYears = array_unique($results);
if ($cleanYears == null)
return response()->json(['error' => true, 'errorCode' => '1008', 'message' => "No years found!"]);
else
return response()->json(['error' => false, 'years' => $cleanYears]);
}
So, the question is, how can i do this in a less expensive way so that my server doesn't time out on every request? Thank in advance for your help :)
NOTE: DB:raw is a no-go as my TL has forbidden me from using it anywhere on the API
Looks like you need the whereBetween:
$between = DB::table('theTable')->whereBetween('data_ini', ["str_to_date('2011-05-06','%Y-%m-%d')", "str_to_date('2011-05-06','%Y-%m-%d')"])->get();
With models:
$between = $this->model->whereBetween('data_ini', ["str_to_date('2011-05-06','%Y-%m-%d')", "str_to_date('2011-05-06','%Y-%m-%d')"])->get();
In the above, I am utilizing MySQL's built-in str_to_date
Hope this helps!
I'm having a little problem and couldn't figure it out. I created a table with checkbox and it's working and can save to json without a problem. Now i wanna make my checkboxes have their default values set from json data when the page loads (to make it easier to edit). Anyway here is my code:
//row index
var index = 0;
//gets full info of student
var responseStudent = rpc.call('db.findOne', ['StudentAnket', {
'_id': '${this.objId}'
}]);
result = responseStudent['result'];
//gets info needed for my table
//{anket: true, request: true, statement: false, etc...}
var resultMat = result['listmaterial'];
//materials is a list which contains id, name of rows
materials.forEach((m) {
//creating table body
index = index + 1;
tbody.append(new Element.tr()
..append(new TableCellElement()..text = index.toString())
..append(new TableCellElement()..append(new LabelElement()
..text = m['name']
..setAttribute('for', m['id'])))
..append(new TableCellElement()..append(new InputElement()
..id = m['id']
..type = "checkbox"
..checked = "VALUE TAKEN FROM JSON")));
});
So how can i get keys and values from resultMat and set checked property for each checkbox?
Edit:
List materials = [{
'id': 'anket',
'name': 'Student anket'
}, {
'id': 'request',
'name': 'Request'
}, {
'id': 'statement',
'name': 'Statement'
}, {
'id': 'marklist',
'name': 'Mark List'
}];
Your information how your materials structure looks like is not clear. A List has only one value not two ('id, 'name of rows'). First you have to ensure that your JSON is not a String but a Dart data structure (Lists, Maps, values).
You can take a look at the answers to this questions to learn how this works
Dart Parse JSON into Table
Then you should be able to access the value like
..checked = resultMat[m['id']] ;
This question already has answers here:
Why does this PDO statement silently fail?
(2 answers)
Closed 18 days ago.
I'm using the following php pdo code to insert data into mysql database, the insertion succeeded, however, the updated database is showing the string literals ':a', ':b' as values in respectively field. what's wrong?
$data = array(
array('a' => 'John', 'b' => 'OK'),
);
$st=$dbh->prepare("insert into mytable (a, b) values(':a', ':b')");
$st->execute($data) or print_r($st->errorInfo());
Remove the quotes from your placeholders. Otherwise, they are treated as string literals and directly inserted.
$st=$dbh->prepare("insert into mytable (a, b) values(:a, :b)");
And remove the nesting on your array:
// $data is an associative array, it should not contain another array!
$data = array('a' => 'John', 'b' => 'OK');
To be consistent, I prefer to use the : on the placeholder array keys:
$data = array(':a' => 'John', ':b' => 'OK');
You need to define your array the same in the sql and the parameters, you're missing the ":". You also don't need two arrays, only one.
$data = array(':a' => 'John', ':b' => 'OK');
The query also does not need quotes, since PDO already knows it's a parameter
$st=$dbh->prepare("insert into mytable (a, b) values(:a, :b)");
$st->execute($data) or print_r($st->errorInfo());
You are executing a prepared statement with named placeholders. So, you need to remove quotes from your placeholders, otherwise they are treated as a values for respective columns and directly updated.
To be consistent, I prefer to use the : on the placeholder array keys:
$data = array(':a' => 'John', ':b' => 'OK');
$st=$dbh->prepare("insert into mytable (a, b) values(:a, :b)");
You can also execute a prepared statement with question mark placeholders:
$data = array(
array('John','OK'),
);
$st=$dbh->prepare("insert into mytable (a, b) values(?, ?)");
$st->execute($data) or print_r($st->errorInfo());