I have code like this:
var hour = 7;
for (var i = 0;i <= 1; i++ ){
var minute = 0;
console.log((i + hour) % 24);
}
when I run it, I get result like this:
7
8
my question: how to add the value in format minute ex: 0-59
so I wanna loop the data like this:
7:0
7:1
7:2
s.d
7:59
8:0
You could use a new array to store all your unique values. You will need to look into the new "uniques" array, if the value alreay exists and then use the default value:
var number= ["1", "2", "3", "4", "5", "6", "6"];
var default = 0;
var uniques = [];
var result = [];
for(var i=0; i < number.length; i++) {
if(!inArray(number[i], uniques) {
uniques.push(number[i]);
result.push(number[i]);
console.log(number[i]);
} else {
console.log(default);
result.push(default);
}
}
function inArray(needle, haystack) {
var length = haystack.length;
for(var i = 0; i < length; i++) {
if(haystack[i] == needle) return true;
}
return false;
}
You could use Array#indexOf and check against the actual index. If you get the same index, then show the element, otherwise use a default value instead.
var number= ["1", "2", "3", "4", "5", "6", "6"];
for (var i = 0; i < number.length;i++) {
console.log(number.indexOf(number[i]) === i ? number[i] : undefined);
}
Use map to get the new array, and in the callback store each item in a set to know if it's a duplicate or not.
var number = ["1", "2", "3", "4", "5", "6", "6"];
var s = new Set();
console.log(number.map(n => s.has(n) ? undefined : s.add(n) && n));
If the non-equality of your values is respected by stringification, you can use a plain object, without needing ES6 features:
var number = ["1", "2", "3", "4", "5", "6", "6"];
var s = Object.create(null);
console.log(number.map(function(n) {
if (n in s) return undefined;
s[n] = true;
return n;
}));
Related
why is it that i am unable to find the index values of the 'deck' array using deck[0] but this notation works for suits[0]
I am trying to find the index values of my 'deck' array but i am unsure why i keep getting 'undefined'.
var deck = [];
var suits = ["diamonds","hearts","clubs","spades"];
var value = ["A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"];
function genDeck()
{
for(var i = 0; i < suits.length; i++)
{
for(var x = 0; x < value.length; x++){
var card = {Value:value[x], Suit:suits[i]};
deck.push(card);
}
}
return deck;
}
window.onload = function () {
genDeck();
};
var randomNum = Math.floor(Math.random() * 52);
You aren't adding anything to the deck array. You need to call
deck.push(card)
EDIT: Here's the working example code:
var deck = [];
var suits = ["diamonds","hearts","clubs","spades"];
var value = ["A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"];
function genDeck()
{
for(var i = 0; i < suits.length; i++)
{
for(var x = 0; x < value.length; x++){
var card = {Value:value[x], Suit:suits[i]};
deck.push(card);
}
}
return deck;
}
window.onload = function () {
genDeck();
console.log('First Item: ', deck[0])
};
var randomNum = Math.floor(Math.random() * 52);
Note that you have to call console.log after you've called genDeck in your window.onload function.
I have a comma separated string in JavaScript that I want to separate into mutiple arrays, for each column but I want to ignore the first couple of lines. So for instance I want to convert the following string,
let data = "test,data,\n,ignore,this,\n,A,B,C,\n,1,2,3,\n,1,2,3";
into arrays like the following.
["A", "1", "1"]
["B", "2", "2"]
["C", "3", "3"]
EDIT
Ths is my initial solution that I tried. Like it works but it's not really a nice solution:/
for (let i = 1; i < out.length; i++)
{
let arr = out[i].split(',');
if (i === 1)
{
for (let j = 0; j < columns; j++)
{
let col = "arr" + j;
console.log(col);
obj[col] = [arr[j]];
}
console.log(obj);
}
else
{
for (let j = 0; j < columns; j++)
{
let col = "arr" + j;
let val = arr[j];
if (j !== "")
{
obj[col].push(val);
}
}
}
}
I should point out that I eventually want to create a map of the letters to corresponding array of numbers and I won't know what the key value will be. So I'll be trying to get something like the following,
"A": ["1", "1"]
"B": ["2", "2"]
"C": ["3", "3"]
You could split by ',\n,' for getting lines and for the items split by comma. Then omit the first two arrays.
var data = "test,data,\n,ignore,this,\n,A,B,C,\n,1,2,3,\n,1,2,3",
result = data.split(',\n,').map(s => s.split(',')).slice(2);
console.log(result);
for your expected result you first have to split a string by ',' and then run for loop on a resulted array and inside that convert, you alphabet with a number and compare numbers if match found than push it into a respective array.
like below code
var datArray= [];
a = [];
b = [];
c = [];
let data = "test,data,\n,ignore,this,\n,A,B,C,\n,1,2,3,\n,1,2,3";
datArray = data.split(',');
for(var i = 0; i < datArray.length; i++) {
if(datArray[i] == 'A' || datArray[i] == 1) {
a.push(datArray[i]);
} else if(datArray[i] == 'B' || datArray[i] == 2) {
b.push(datArray[i]);
} else if(datArray[i] == 'C' || datArray[i] == 3) {
c.push(datArray[i]);
}
}
console.log(a);
console.log(b);
console.log(c);
this is one of the way you can do...
This method is not hard coded ! With this method you can handle :
ABCDEF.... , 1 2 3 4 5 6 ...
We will split for first action. Then detect Not A Number function isNaN to detect A B C .
Array helpers :
var notNumber = [];
var numbers = [];
to store data .
On the end generate your results arrays !
Try this :
var data = "test,data,\n,ignore,this,\n,A,B,C,\n,1,2,3,\n,1,2,3";
var handler = data.split(",");
var preventFlag = true;
var countNaN = 0;
var notNumber = [];
var numbers = [];
//console.log(handler);
for (var x = 0;x < handler.length;x++) {
var currentData = handler[x];
if (preventFlag == false) {
if ( isNaN(currentData) ) {
notNumber.push(currentData);
}
else {
if (currentData != "\n") {
numbers.push(currentData);
}
}
}
if (currentData == "this"){
preventFlag = false;
}
}
//console.log(notNumber)
//console.log(numbers)
for (var z = 0; z < notNumber.length;z++) {
window["result" + z] = [];
window["result" + z].push(notNumber[z]);
//console.log(window["result0"])
window["result" + z].push(numbers[z])
window["result" + z].push(numbers[z + (notNumber.length) ])
}
// GENERATE RESULT ARRAY
console.log(window["result0"]);
console.log(window["result1"]);
console.log(window["result2"]);
//["A", "1", "1"]
//["B", "2", "2"]
//["C", "3", "3"]
This question already has answers here:
Get all unique values in a JavaScript array (remove duplicates)
(91 answers)
Closed 6 years ago.
I want to push values of 3 arrays in a new array without repeating the same values
var a = ["1", "2", "3"];
var b = ["3", "4", "5"];
var c = ["4", "5", "6"];
var d = [];
function newArray(x, y, z) {
for(var i = 0; i < d.length; i++) {
if(d.length == -1) {
d[i].push(a[i])
}
}
for(var i = 0; i < d.length; i++) {
if(d.length == -1) {
d[i].push(y[i])
}
}
for(var i = 0; i < d.length; i++) {
if(d.length == -1) {
d[i].push(z[i])
}
}
}
newArray(a, b, c);
d = ["1", "2", "3", "4", "5", "6"];
You can use concat() and Set together as below,
var a = ["1","2","3"];
var b = ["3","4","5"];
var c = ["4","5","6"];
var d = a.concat(b).concat(c);
var set = new Set(d);
d = Array.from(set);
console.log(d);
If your goal is to remove duplicates, you can use a set,
var arr = [1, 2, 3, 4, 5, 5, 6, 6, 6, 7]
var mySet = new Set(arr)
var filteredArray = Array.from(mySet)
console.log(filteredArray.sort()) // [1,2,3,4,5,6,7]
var a = ["1","2","3"]
, b = ["3","4","5"]
, c = ["4","5","6"]
, d = [];
function newArray(x,y,z) {
x.concat(y,z).forEach(item =>{
if (d.indexOf(item) == -1)
d.push(item);
});
return d;
}
console.log(newArray(a,b,c));
You could save yourself some time and effort with the very useful utility library Lodash.
The function you're looking for is Union
As stated by Lodash:
Creates an array of unique values, in order, from all given arrays
using SameValueZero for equality comparisons.
Example
_.union([2], [1, 2]);
// => [2, 1]
var a = ["1", "2", "3"];
var b = ["3", "4", "5"];
var c = ["4", "5", "6"];
var d = [];
var hash = [];
AddToHash(a);
AddToHash(b);
AddToHash(c);
function AddToHash(arr) {
for (var i = 0; i < arr.length; i++) {
if (!hash[arr[i]]) {
hash[arr[i]] = 1;
} else
hash[arr[i]] += 1;
}
}
for (var i = 0; i < hash.length; i++) {
d.push(i);
}
console.log(d);
Hope this helps
Here is another version:
var d = b.concat(c);
d.forEach(function(el) {
if (a.indexOf(el) === -1) {
a.push(el)
}
})
ES6 version:
let d = b.concat(c);
d.forEach(el => {
if (a.indexOf(el) === -1) {
a.push(el)
}
})
I am new to js and trying to sort an array of objects by two fields - starting with the first property, and then by the second property. Both properties are numbers.
The data is:
var homes = [{
"h_id": "3",
"minimumorder": "12",
"price": "17"
}, {
"h_id": "4",
"minimumorder": "1",
"price": "20"
}, {
"h_id": "5",
"minimumorder": "1",
"price": "18.10"
}
There are more objects in the array, this is a simplified example. The below code ALMOST gets me there, but for the minimumorder property it puts 12 after 1 instead of after 6:
cmp = function(a, b) {
parseFloat(a);
parseFloat(b);
if (a > b) return +1;
if (a < b) return -1;
return 0;
}
homes.sort(function(a, b) {
return cmp(a.minimumorder,b.minimumorder) || cmp(a.price,b.price)
})
jsFiddle here.
Any help would be HUGELY appreciated, as I've been googling and tinkering for hours trying to figure this out.
You need to reassign the parsed value back to a and b:
a = parseFloat(a);
b = parseFloat(b);
Otherwise it ends up comparing strings, and 12 occurs after 1 lexically, just like the word at comes after a in the dictionary.
Updated fiddle.
Well,
You should use a code like this:
function sortHomes(homes)
{
var temp_homes = new Array();
var new_homes = new Array();
for(var i = 0; i < homes.length; i++) temp_homes[i] = homes[i];
var maximum = 0, minimum;
for(i = 0; i < temp_homes.length; i++) maximum = Math.max(maximum, temp_homes.minimumorder);
var min_price, j, k, indexes, price_indexes;
for(i = 0; i < temp_homes.length; i++){
minimum = maximum;
for(j = 0; j < temp_homes.length; j++){
minimum = Math.min(minimum, temp_homes[j].minimumorder);
}
indexes = getIndexes(temp_homes, minimum, "minimumorder");
if(indexes.length == 1){
new_homes.push(temp_homes[indexes[0]]);
temp_homes[indexes[0]].minimumorder = maximum + 1;
}
else{
for(j = 0; j < indexes.length; j++){
min_price = maximum;
for(k = 0; k < indexes.length; k++){
min_price = Math.min(min_price, temp_homes[indexes[k]].price);
}
price_indexes = getIndexes(temp_homes, min_price, "price");
for(k = 0; k < price_indexes.length; k++){
new_homes.push(temp_homes[price_indexes[k]]);
temp_homes[price_indexes[k]].price = maximum + 1;
}
}
}
}
}
function getIndexes(arr, el, name)
{
var indexes = new Array();
for(var i = 0; i < arr.length; i++) if(arr[i][name] == el) indexes.push(i);
return indexes;
}
It should work.
If it doesn't, please inform me about it.
Oh, and in order to sort homes, just use:
homes = sortHomes(homes);
How can i use a binary search to compare two arrays and count the number of times it matched, i did find some here where one item was compared to an array..follwing is regular one for example ..thanx for the help.
var a = ["1", "2", "3", "4", "5", "6", "7"];
var b = ["8", "1", "3", "9", "4", "6", "8"];
var count = 0;
for (i = 0; i < a.length; i++) {
for (j = 0; j < b.length; j++) {
if (a[i] == b[j]) count += 1;
}
}
document.write(count);
I tried to do this ..
for (i = 0; i < a.length; i++) {
var left = 0;
var right = b.length - 1;
while (left <= right) {
var mid = parseInt((left + right) / 2);
if (b[mid] == a[i]) {
count += 1;
} else if (b[mid] < a[i]) {
left = mid + 1;
}
else {
right = mid - 1;
}
}
}
document.write(count);
Linearly go through the b array and use a binary search of the a array.
function binarySearch(a, value) {
var left = 0;
var right = a.length - 1;
while (left <= right) {
var mid = (left + right) >> 1;
if (a[mid] === value) {
return mid;
} else if (a[mid] < value) {
left = mid + 1;
}
else {
right = mid - 1;
}
}
return -1;
}
var a = ["1", "2", "3", "4", "5", "6", "7"];
var b = ["8", "1", "3", "9", "4", "6", "8"];
var count = 0;
b.forEach(function(value) { if (binarySearch(a, value) >= 0) ++count; });