Assigning values to every other index in an array - arrays

I have three arrays that correlate to one another (Users, Wins, and Lost), Wins[0] through Wins[2] stand for Users[0] through Users[2]. If Users[0] through Users[2] won and Users[3] as well as Users[4] lost, then Lost[3] and Lost[4] need to be equal to 1.
var Users = ["user1", "user2", "user3", "user4", "user5"];
var Wins = ["1", "1", "1", "0", "0"];
var Lost = ["0", "0", "0", "0", "0"]; //Lost[3] and Lost[4] need to be equal to 1

You can simply use map and a ternary operator to produce the Lost array:
var Users = ["user1", "user2", "user3", "user4", "user5"];
var Wins = ["1", "1", "1", "0", "0"];
var Lost = Wins.map((win) => win === "1" ? "0" : "1");
console.log(Lost);

const lost = wins.map(w => w === "1" ? "0" : "1");

Related

Split the array and get value [React native]

I am developing the react native application and I want to split the array but I can't understand how to do that,
[{"dtCreatedOn": "2021-06-01T03:28:21.450Z", "flgIsActive": true, "inTagId": 2, "stTags": "Song"}, "3", "6", "7", "8"]
I have something like the above array, I want to get the value of the inTagId and also last integer value "3", "6", "7", "8" from this array
var a = [{"dtCreatedOn": "2021-06-01T03:28:21.450Z", "flgIsActive": true, "inTagId": 2, "stTags": "Song"}, "3", "6", "7", "8"]
var tagID = a[0].inTagId
var b = Object.keys(a)
var lastInteger = b[(b.length-1)]
var test = [{"dtCreatedOn": "2021-06-01T03:26:44.910Z", "flgIsActive": true, "inTagId": 1, "stTags": "Emotion"},"4","5","6"]
var tags = [];
test.map(function(ele) {
if(typeof ele === 'object')
{
tags.push(ele.inTagId);
}
else
{
tags.push(ele)
}
});
tags.join(',')

get data of first two index from json response

Hello i am new to swift and i am calling API through Alamofire and SwiftyJON and i am able to retrive response successfully but from that data i want to retrive only first two index of data let me explain you in brief
Here is my response
{
"previous_inspection_list" : [
{
"inspection_number" : "3",
"date_inspected" : "2019-04-13",
"fk_properties_id" : "2",
"created_by" : "3",
"signature" : "img_ZbsOx3fx1r1555154350.png",
"status" : "1",
"fk_user_id" : "3",
"signature_name" : "Vishal Parmar",
"created_date" : "2019-04-13 05:19:10",
"updated_by" : "0",
"inspections_id" : "8",
"updated_date" : "0000-00-00 00:00:00"
},
{
"inspection_number" : "2",
"date_inspected" : "2019-04-13",
"fk_properties_id" : "2",
"created_by" : "3",
"signature" : "img_uVQw3K4pfY1555140089.png",
"status" : "1",
"fk_user_id" : "3",
"signature_name" : "Vishal Parmar",
"created_date" : "2019-04-13 01:21:29",
"updated_by" : "0",
"inspections_id" : "6",
"updated_date" : "0000-00-00 00:00:00"
},
{
"inspection_number" : "1",
"date_inspected" : "2019-04-13",
"fk_properties_id" : "2",
"created_by" : "2",
"signature" : "img_g6GrjsofPE1555137646.png",
"status" : "1",
"fk_user_id" : "2",
"signature_name" : "Mihir Panchasara",
"created_date" : "2019-04-13 00:40:46",
"updated_by" : "0",
"inspections_id" : "3",
"updated_date" : "0000-00-00 00:00:00"
}
],
"success" : "1",
"message" : "Successfully."
}
as you can able to see my response now i want to retrive only first two index value like below
Expected OutPut
for 1st index expected output
{
"inspection_number" : "3",
"date_inspected" : "2019-04-13",
"fk_properties_id" : "2",
"created_by" : "3",
"signature" : "img_ZbsOx3fx1r1555154350.png",
"status" : "1",
"fk_user_id" : "3",
"signature_name" : "Vishal Parmar",
"created_date" : "2019-04-13 05:19:10",
"updated_by" : "0",
"inspections_id" : "8",
"updated_date" : "0000-00-00 00:00:00"
}
2nd Index Expected Output
{
"inspection_number" : "2",
"date_inspected" : "2019-04-13",
"fk_properties_id" : "2",
"created_by" : "3",
"signature" : "img_uVQw3K4pfY1555140089.png",
"status" : "1",
"fk_user_id" : "3",
"signature_name" : "Vishal Parmar",
"created_date" : "2019-04-13 01:21:29",
"updated_by" : "0",
"inspections_id" : "6",
"updated_date" : "0000-00-00 00:00:00"
}
let me show you my code which i have tried
let sampleArray = data.array
let firstdict = sampleArray![0]
print(firstdict)
let signature_name = firstdict["signature_name"].stringValue
let inspection_number = firstdict["inspection_number"].stringValue
let date_inspected = firstdict["date_inspected"].stringValue
let inspections_id = firstdict["inspections_id"].stringValue
self.lblFirstInspName.text = signature_name
self.lblInspNumber.text = "#\(inspection_number)"
self.lblFirstInspDate.text = date_inspected
self.inspID1 = inspections_id
let secondDict = sampleArray![1]
let signature_name1 = secondDict["signature_name"].stringValue
let inspection_number1 = secondDict["inspection_number"].stringValue
let date_inspected1 = secondDict["date_inspected"].stringValue
let inspections_id2 = secondDict["inspections_id"].stringValue
self.lblSeconfInspName.text = signature_name1
self.lblSecondInspNumber.text = "#\(inspection_number1)"
self.lblSecondInspDate.text = date_inspected1
self.inspID2 = inspections_id2
please see my code i am getting output as expected but when in response there is only one data then i am getting crash on second index because there is no data at second index
please someone help me
Add a safe check before fetching the second one
if let sampleArray = sampleArray, sampleArray.count > 1 {
let secondDict = sampleArray[1]
let signature_name1 = secondDict["signature_name"].stringValue
let inspection_number1 = secondDict["inspection_number"].stringValue
let date_inspected1 = secondDict["date_inspected"].stringValue
let inspections_id2 = secondDict["inspections_id"].stringValue
self.lblSeconfInspName.text = signature_name1
self.lblSecondInspNumber.text = "#\(inspection_number1)"
self.lblSecondInspDate.text = date_inspected1
self.inspID2 = inspections_id2
}
Try this function. I tried to put the important points inside the code.
func analysis() {
let rawData = data as! [String: Any] // Specify value type -> By doing this, you specify the type of value that is "JSON"
let arrayPreviousInspectionList = rawData["previous_inspection_list"] as! [[String: String]] // Getting "previous_inspection_list" and specifying its type -> it's list of [String: String]
if(arrayPreviousInspectionList.count >= 2) { // You must check the number of objects in the list
// first index
let firstInspection = arrayPreviousInspectionList[0]
let signature_name = firstInspection["signature_name"]!
let inspection_number = firstInspection["inspection_number"]!
let date_inspected = firstInspection["date_inspected"]!
let inspections_id = firstInspection["inspections_id"]!
self.lblFirstInspName.text = signature_name
self.lblInspNumber.text = "#\(inspection_number)"
self.lblFirstInspDate.text = date_inspected
self.inspID1 = inspections_id
// second index
let secondInspection = arrayPreviousInspectionList[1]
let signature_name1 = secondInspection["signature_name"]!
let inspection_number1 = secondInspection["inspection_number"]!
let date_inspected1 = secondInspection["date_inspected"]!
let inspections_id2 = secondInspection["inspections_id"]!
self.lblSeconfInspName.text = signature_name1
self.lblSecondInspNumber.text = "#\(inspection_number1)"
self.lblSecondInspDate.text = date_inspected1
self.inspID2 = inspections_id2
} else {
print("--- The number of inspections is less than 2")
}
}
Hope to be useful. Also sorry about my English.

How to know array contents are empty

Lets say I have array like this :
[
{
"id" : "1"
"name": "David",
"age": "20"
},
{
"id" : "2"
"name": "",
"age": "18"
},
{
"id" : "3"
"name": "Micheal",
"age": "25"
},
{
"id" : "4"
"name": "Wonder Women",
"age": "20"
},
{
"id" : "5"
"name": "Clark",
"age": ""
}
]
Some of the contents are empty. How to write the condition if "age" is null and "name" is null.
You can filter the array and then use it where you need:
const myFilteredArray = arr.filter(item => {
return item.name !== null && item.age !== null
})
// use myFilteredArray in your code.
As your request is not definitive, I'm assuming you want the person elements that satisfy your criteria in a new array, called personsWithoutNameAndAge.
You can achieve this very elegantly, using functional programming:
const personsWithoutNameAndAge = persons.filter(person => !person.name && !person.age)
The filter() method creates a new array with all elements that pass the test implemented by the provided function.
The function we provide the filter function (the argument passed to it) only passes the test (returns true) if both person.name and person.age are falsy. Empty string, undefined, and null are all falsy and so the function will successfully work with any of these values representing 'null'.
Hope this helps!

how to use for loop make an array which contains something like a dictionary

I want to create an array something like this
array=["1":"1","2":"2","3":"3","4":"4","5":"5","6":"6","7":"7","8":"8"]
It's something like a dictionary, every value needs to be a key:value pair,
so my problem is how to init this type of array? The following is my work, it doesn't work.
array=[String:String]()
for i in 0...7{
array.append(String(i):String(i))
}
every line has a bug!!
plz help
Its not something like Dictionary it is Dictionary, if you want to make a dictionary you can go like this way.
var dictionary = [String:String]()
for i in 0...7{
dictionary[String(i)] = String(i)
}
print(dictionary)
["0":"0","1":"1","2":"2","3":"3","4":"4","5":"5","6":"6","7":"7"]
In addition to Nirav D's answer; I feel the following may help:
There is a method updateValue(_:​for​Key:​) that updates (or adds new key-value pair if the key does not exist) the value for given key.
So your code would look like this:
var array = [String:String]()
for i in 0...7 {
array.updateValue(String(i), forKey: String(i))
}
print(array)
// Output
["2": "2", "1": "1", "6": "6", "4": "4", "3": "3", "7": "7", "0": "0", "5": "5"]
Swift is always amazing you can define += operator that make it easier. So the code will be as follows:
// Defining += operator
func += <K, V> (inout left: [K:V], right: [K:V]) {
for (k, v) in right {
left.updateValue(v, forKey: k)
}
}
// Usage
var array = [String:String]()
for i in 0...7{
array += [String(i):String(i)]
}
print(array)
// Output
["2": "2", "1": "1", "6": "6", "4": "4", "3": "3", "7": "7", "0": "0", "5": "5"]

Create arrays from 1D array after every nth occurrence using Angular JS

I have an array which looks like this
Array[20]
0 : "2"
1 : "3"
2 : "4"
3 : "5"
4 : "6"
5 : "7"
6 : "8"
7 : "9"
8 : "10"
9 : "11"
10: "12"
11: "13"
12: "14"
13: "15"
14: "16"
15: "17"
16: "18"
17: "19"
18: "20"
19: "12"
Now I want to create arrays after every 4th occurrence like this
First Array
0 : "2"
1 : "6"
2 : "10"
3 : "14"
4 : "18"
Second Array
0 : "3"
1 : "7"
2 : "11"
3 : "15"
4 : "19"
and so on...
Yet I have written this code
for (var i = 0; i < $scope.data.effort.length; i = i+ 4) {
efforts.push( $scope.data.effort[i]);
};
From above code I am getting only first array what should I need to do to get remaining arrays. Please help
All you need is to run an extra loop outside that which handles your starting index. LIke this:
efforts = []
for (var j = 0; j < arr.length / 4; j++) {
efforts[j] = []
for (var i = j; i < arr.length; i = i + 4) {
efforts[j].push(arr[i]);
};
console.log(efforts[j])
}
Here's working example: (simplified in JS, without $scope and all)
var arr = [
"2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14",
"15", "16", "17", "18", "19", "20", "12"
]
efforts = []
for (var j = 0; j < arr.length / 4; j++) {
efforts[j] = []
for (var i = j; i < arr.length; i = i + 4) {
efforts[j].push(arr[i]);
};
console.log(efforts[j])
}
Or, interestingly, you can use the beast, I mean, reduce to achieve the same. :)
var arr = [
"2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14",
"15", "16", "17", "18", "19", "20", "12"
]
efforts = arr.reduce(function(arr, cur, curIndex) {
arr[curIndex % 4] = arr[curIndex % 4] || [];
arr[curIndex % 4].push(cur);
return arr
}, [])
console.log(efforts)
Another simple way with array filter:
var originalArray =["2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19","20","21"];
var firstArray = originalArray.filter((el, index) => (index%4 === 0));
var secondArray = originalArray.filter((el, index) => (index%4 === 1));
and so on

Resources