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 7 years ago.
Improve this question
There is two array,
One -> ["A","B","C","D"]
Two -> ["A","E","H","D"]
I need check array details. I mentioned array one is existing data (before updating) and array two is update data ( after update the array one). I need figure out which data is come into that array (array two ) and which data is remove from that array (array one).
Look into http://underscorejs.org/#arrays functions, you need to use _.intersection and _.difference methods. It's pretty easy to code that functions by yourself if you don't want new dependencies
_.intersection(One, Two) -> not changed data
_.difference(Two, One) -> new data
_.difference(One, Two) -> removed data
jQuery(function() {
var array1 = ["A", "B", "C", "D"];
var array2 = ["A","H","J","D"];
var foo1 = [];
var foo2 = [];
var i = 0;
jQuery.grep(array2, function(el) {
if (jQuery.inArray(el, array1) == -1) foo1.push(el);
i++;
});
jQuery.grep(array1, function(e2) {
if (jQuery.inArray(e2, array2) == -1) foo2.push(e2);
i++;
});
alert(" Removed Data is " + foo2);
alert(" New Data is " + foo1);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I'm trying to define append values to an array within a Struct however I get the below error:
Type '()' cannot conform to 'View'; only struct/enum/class types can conform to protocols
I have define a structure for my functions:
struct Functions {
//CURRENCY FORMATTING
I'm using the below code to create an array of localeIdentifiers and corresponding description:
let localeSheet: [(id: String, name: String)] = {
Locale.availableIdentifiers.map {
(id: $0, name: (NSLocale.current as NSLocale).displayName(forKey: .identifier, value: $0) ?? "-")
}.sorted { $0.name < $1.name }
}()
I have defined an array:
var localeIdentifiersX = [String]()
And now trying to append values to that array:
func currencyFormatters() {
ForEach(0 ..< localeSheet.count) {
localeIdentifiersX.append(localeSheet[$0].id)
//print(localeSheet[$0].id)
}
}
This is where the error is displayed.
Thank you
ForEach (with capital F) is a view builder and its body must return a View.
If you insist on using foreach you should do it like:
func currencyFormatters() {
(0 ..< localeSheet.count).forEach {
localeIdentifiersX.append(localeSheet[$0].id)
//print(localeSheet[$0].id)
}
}
Also, you can convert all elements of an array to another format at once with the map function like:
let localeIdentifiersX = localeSheet.map { $0.id }
And then use the result to build your SwiftUI's view.
Thanks again.
I mapped as per suggested:
That's a simple one liner localeIdentifiersX = localeSheet.map(.id)
Also used a standard for loop to iterate through the arrays for further processing.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
Hello I have this piece of code :
let mut quotations: Vec<CreateQuotationArgs> = Vec::new();
let mut insert_documents = Vec::new();
while let bson::Bson::Document(document) = bson::to_bson("ations.pop()).unwrap() {
insert_documents.push(document);
}
I would like to perform the same operation (putting quotation in a document BSON) but without using pop() method to keep quotations vector filled.
I know that I could use map() and iter() method but is that the best way to do it ?
"Best" is quite loaded. It's hard to answer that properly without broader context.
The following is equivalent to your original code (assuming you don't care about the order), but without removing items from quotations:
let quotations: Vec<CreateQuotationArgs> = Vec::new();
let mut insert_documents = Vec::new();
for quotation in "ations {
if let bson::Bson::Document(document) = bson::to_bson(quotation).unwrap() {
insert_documents.push(document);
} else {
break;
}
}
A more idiomatic approach would be to not mutate any vectors and instead collect the results into a new one:
let quotations: Vec<CreateQuotationArgs> = Vec::new();
let insert_documents: Vec<_> = quotations
.iter()
.filter_map(|quotation| {
if let bson::Bson::Document(document) = bson::to_bson(quotation).unwrap() {
Some(document)
} else {
None
}
})
.collect();
This isn't exactly the same because it will continue to parse items even after it comes across one that is not a Bson::Document. What's good about it though is that it avoids mutable variables.
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 4 years ago.
Improve this question
I am unable to check if something is string or not.
I have this array:
ji1 = [:Districts,:Winter_Rain, :Hot_Weather_Rain, :South_West_Monsoon, :North_West_Monsoon, :Total]
I am trying to map this array using this code:
hash_data = ji1.map do |el|
{title:el, field:el, sorter:"string", editor:true}
end
This works, but when I use this array:
ji1 = ["Districts",:Winter_Rain, :Hot_Weather_Rain, :South_West_Monsoon, :North_West_Monsoon, :Total]
with this code,
hash_data = ji1.map do |el|
hash_data = ji.map do |el|
if el == "Districts"
abort(el)
else
puts el
end
{title:el, field:el, sorter:"string", editor:true}
end
When I am using code above I don't see any action I am expecting to abort the code when el == "Districts". I need to compare my first array.
While you have an array of symbols you are comparing it with string. Converting the element to string (el.to_s == "Districts") will work.
ji1 = [
:Districts, :Winter_Rain, :Hot_Weather_Rain, :South_West_Monsoon,
:North_West_Monsoon, :Total
]
hash_data = ji1.map do |el|
if el.to_s == "Districts"
abort(el)
else
puts el
end
{ title:el, field:el, sorter:"string", editor:true }
end
Note: The above code only converts el to string for comparison purpose. If you want it String in the return value you might want to change el in the loop itself
Like this:
hash_data = ji1.map do |el|
el = el.to_s
...
...
end
I have a quiz game in flash; basically you need to type the answer to answer 4 questions. In the end, it will show you the score and your answers vs. The correct answers.
I need help on how to randomize the questions (without repeating the question)
In the end the correct answer needs to match the order in which the player answered the question.
I attached the pictures below.
The code: Frame 1
stop();
var nQNumber:Number = 0;
var aQuestions:Array = new Array();
var aCorrectAnswers:Array = new Array("Jupiter", "Mars", "war", "Titan");
var aUserAnswers:Array = new Array();
aQuestions[0] = "What is the biggest planet in our solar system?";
aQuestions[1] = "Which planet in our solar system is the 4th planet from the
sun?";
aQuestions[2] = "Mars is named after the Roman god of ___.";
aQuestions[3] = "What is the name of Saturn's largest moon?";
questions_txt.text = aQuestions[nQNumber];
submit_btn.addEventListener(MouseEvent.CLICK, quiz);
function quiz(e:MouseEvent):void{
aUserAnswers.push(answers_txt.text);
answers_txt.text = "";
nQNumber++;
if(nQNumber < aQuestions.length){
questions_txt.text = aQuestions[nQNumber]}
else{
nextFrame()}
}
Frame 2
var nScore:Number = 0;
for(var i:Number = 0; i < aQuestions.length; i++){
this["userAnswer" + i + "_txt"].text = aUserAnswers[i];
this["correctAnswer" + i + "_txt"].text = aCorrectAnswers[i];
if(aUserAnswers[i].toUpperCase() == aCorrectAnswers[i].toUpperCase()){
nScore++}
if(i == aQuestions.length - 1){
score_txt.text = nScore.toString()}}
A common way to handle this, would be to create an array to hold your questions that need to be asked, randomize the array, then remove the corresponding question from the array at the time it is asked. Then when that array is empty, move on to your recap screen.
Here is one of many ways you could accomplish this:
First, let's simplify this by using objects instead of a whole bunch of arrays. Your object will have properties for all the relevant information
//create an array that will hold all your questions
var questions:Array = [];
//add a new question object to the array, repeat for all questions
questions.push({
question: "What is the biggest planet in our solar system?",
correctAnswer: "Jupiter"
userAnswer: null,
correct: false
});
Next, let's randomize that array:
//sort the array with the sort function below
questions.sort(randomizeArray);
//this sorts in a random way
function randomizeArray(a,b):int {
return(Math.random() > 0.5) ? 1: -1;
}
Now, let's copy the array to keep track of which questions need to be asked still
var askQuestions:Array = questions.concat(); //concat with no parameters returns a new shallow copy of the array
var curQuestion; //create a var to hold the current question
Now, create a function to ask the next question:
function askNextQuestion():void {
//check if there are any more questions to ask
if(askQuestions.length > 0){
//get the next question object
curQuestion = askQuestions.shift(); //shift removes the first item of an array, and returns that item
questions_txt.text = curQuestion.question;
answers_txt.text = "";
}else{
//all questions have been asked, show your recap screen
finish();
}
}
You'll need a function to run when you click the answer button:
function submitAnswer(e:Event = null):void {
//if there is a current question
if(curQuestion){
curQuestion.userAnswer = answers_txt.text;
curQuestion.correct = curQuestion.correctAnswer.toUpperCase() == answers_txt.text.toUpperCase();
}
//ask the next question
askNextQuestion();
}
And a function that runs when all questions have been asked:
function finish():void {
var score:int = 0;
//go through the array and count how many are correct and recap
for(var i:int=0; i<questions.length;i++){
if(questions[i].correct) score++;
trace("Question " + (i+1) + ":",questions[i].question); //arrays are 0 based, so we add 1 to the index (i) so that it says "Question 1:" for the first question instead of "Question 0:"
trace("You answered:",questions[i].userAnswer);
trace("Correct Answer:", questions[i].correctAnswer);
trace(questions[i].correct ? "You were correct" : "You were wrong","\n"); //this is shorthand if statement, \n is a line break
}
score_txt.text = score + " out of " + questions.length;
}
And of course, to get things started you just do: askNextQuestion()
Are you looking for the nifty feature called Math.random()? Multiply the result of Math.random() by your desired random generation range, round it, and select a random question in your array using the number.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 5 years ago.
Improve this question
I have a web app (AngularJS, WebAPI, MVC...), I use ES6 new features.
Everything works like a charm in Chrome.
The problem is with IE (we have IE 11 at work).
IE doesnt like few things, such as:
Object doesn't support property or method 'find' and other ES6 functions.
I have heard of polyfill scrips that I can add to my app so that it will work in IE as well.
I dont know what polyfill script I need and there to find it.
Can someone assist? Thanks.
for polyfill script use es6 shim:
https://github.com/paulmillr/es6-shim
if your object is array
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/find
if (!Array.prototype.find) {
Object.defineProperty(Array.prototype, 'find', {
value: function(predicate) {
// 1. Let O be ? ToObject(this value).
if (this == null) {
throw new TypeError('"this" is null or not defined');
}
var o = Object(this);
// 2. Let len be ? ToLength(? Get(O, "length")).
var len = o.length >>> 0;
// 3. If IsCallable(predicate) is false, throw a TypeError exception.
if (typeof predicate !== 'function') {
throw new TypeError('predicate must be a function');
}
// 4. If thisArg was supplied, let T be thisArg; else let T be undefined.
var thisArg = arguments[1];
// 5. Let k be 0.
var k = 0;
// 6. Repeat, while k < len
while (k < len) {
// a. Let Pk be ! ToString(k).
// b. Let kValue be ? Get(O, Pk).
// c. Let testResult be ToBoolean(? Call(predicate, T, « kValue, k, O »)).
// d. If testResult is true, return kValue.
var kValue = o[k];
if (predicate.call(thisArg, kValue, k, o)) {
return kValue;
}
// e. Increase k by 1.
k++;
}
// 7. Return undefined.
return undefined;
}
});
}