Snippets Collections
cars.some(car => car.color === "red" && car.type === "cabrio");
// output: true

cars.every(car => car.capacity >= 4);
// output: false
let sortedCars = cars.sort((c1, c2) => (c1.capacity < c2.capacity) ? 1 : (c1.capacity > c2.capacity) ? -1 : 0);
console.log(sortedCars);
// output:
// [
//   {
//     color: 'purple',
//     type: 'minivan',
//     registration: 'Wed Feb 01 2017 00:00:00 GMT+0100 (GMT+01:00)',
//     capacity: 7
//   },
//   {
//     color: 'red',
//     type: 'station wagon',
//     registration: 'Sat Mar 03 2018 01:00:00 GMT+0100 (GMT+01:00)',
//     capacity: 5
//   },
//   ...
// ]
cars.forEach(car => {
 car['size'] = "large";
 if (car.capacity <= 5){
   car['size'] = "medium";
 }
 if (car.capacity <= 3){
   car['size'] = "small";
 }
});
cars.forEach(car => {
 car['size'] = "large";
 if (car.capacity <= 5){
   car['size'] = "medium";
 }
 if (car.capacity <= 3){
   car['size'] = "small";
 }
});
let sizes = cars.map(car => {
  if (car.capacity <= 3){
    return "small";
  }
  if (car.capacity <= 5){
    return "medium";
  }
  return "large";
});
console.log(sizes);
// output:
// ['large','medium','medium', ..., 'small']

//create a new object if we need more values:

let carsProperties = cars.map(car => {
 let properties = {
   "capacity": car.capacity,
   "size": "large"
 };
 if (car.capacity <= 5){
   properties['size'] = "medium";
 }
 if (car.capacity <= 3){
   properties['size'] = "small";
 }
 return properties;
});
console.log(carsProperties);
// output:
// [
//   { capacity: 7, size: 'large' },
//   { capacity: 5, size: 'medium' },
//   { capacity: 5, size: 'medium' },
//   { capacity: 2, size: 'small' },
//   ...
// ]
function componentToHex(c) {
  var hex = c.toString(16);
  return hex.length == 1 ? "0" + hex : hex;
}

function rgbToHex(r, g, b) {
  return "#" + componentToHex(r) + componentToHex(g) + componentToHex(b);
}

alert(rgbToHex(0, 51, 255)); // #0033ff

//OR

function hexToRgb(hex) {
  var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
  return result ? {
    r: parseInt(result[1], 16),
    g: parseInt(result[2], 16),
    b: parseInt(result[3], 16)
  } : null;
}

alert(hexToRgb("#0033ff").g); // "51";

//hexToRgb() that also parses a shorthand hex triplet such as "#03F"
function hexToRgb(hex) {
  // Expand shorthand form (e.g. "03F") to full form (e.g. "0033FF")
  var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
  hex = hex.replace(shorthandRegex, function(m, r, g, b) {
    return r + r + g + g + b + b;
  });

  var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
  return result ? {
    r: parseInt(result[1], 16),
    g: parseInt(result[2], 16),
    b: parseInt(result[3], 16)
  } : null;
}

alert(hexToRgb("#0033ff").g); // "51";
alert(hexToRgb("#03f").g); // "51";
function createEqualLengthArray(array1, array2) {
    while(array1.length < array2.length) {
        console.log(array1.length, array2.length)
        let randIdx = Math.floor(Math.random() * array2.length);
        let randElement = array2.splice(randIdx, 1)[0];
        array1.push(randElement)
    }
    return {hand1: array1, hand2: array2}
}
const pokemonCard = [
			{ id: 4, name: "Charmander", type: "fire", base_experience: 62 },
			{ id: 7, name: "Squirtle", type: "water", base_experience: 63 },
			{ id: 11, name: "Metapod", type: "bug", base_experience: 72 },
			{ id: 12, name: "Butterfree", type: "flying", base_experience: 178 },
			{ id: 25, name: "Pikachu", type: "electric", base_experience: 112 },
			{ id: 39, name: "Jigglypuff", type: "normal", base_experience: 95 },
			{ id: 94, name: "Gengar", type: "poison", base_experience: 225 },
			{ id: 133, name: "Eevee", type: "normal", base_experience: 65 },
		],

let hand1 = [];
let hand2 = [...this.props.pokemonCards]
const hands = createEqualLengthArray(hand1, hand2)
const padToThreeDigits = (num) => (num <= 999 ? `00${num}`.slice(-3) : num); 
function randomEl(array) {
	const idx = Math.floor(Math.random() * array.length);
	return array[idx];
}
function removeAllItems(arr, value) {
  var i = 0;
  while (i < arr.length) {
    if (arr[i] === value) {
      arr.splice(i, 1);
    } else {
      ++i;
    }
  }
  return arr;
}

console.log(removeAllItems([2,5,9,1,5,8,5], 5))
function remove(array, el) {
	const index = array.indexOf(el);
	if (index > -1) {
		const foundEl = array.splice(index, 1);
        return foundEl;
	}
    return undefined;
}
console.log(remove([2,5,9,1,5,8,5], 5))
Example: Shuffle Deck of Cards

// program to shuffle the deck of cards

// declare card elements
const suits = ["Spades", "Diamonds", "Club", "Heart"];
const values = [
  "Ace",
  "2",
  "3",
  "4",
  "5",
  "6",
  "7",
  "8",
  "9",
  "10",
  "Jack",
  "Queen",
  "King",
];

// empty array to contain cards
let deck = [];

// create a deck of cards
for (let i = 0; i < suits.length; i++) {
    for (let x = 0; x < values.length; x++) {
        let card = { Value: values[x], Suit: suits[i] };
        deck.push(card);
    }
}

// shuffle the cards
for (let i = deck.length - 1; i > 0; i--) {
    let j = Math.floor(Math.random() * i);
    let temp = deck[i];
    deck[i] = deck[j];
    deck[j] = temp;
}

console.log('The first five cards are:');

// display 5 results
for (let i = 0; i < 5; i++) {
    console.log(`${deck[i].Value} of ${deck[i].Suit}`)
}

//output
The first five cards are:
4 of Club
5 of Diamonds
Jack of Diamonds
2 of Club
4 of Spades
function shuffle(array) {
  const curIdx = array.length;

  // While there remain elements to shuffle...
  while (0 !== cur_idx) {
    // Pick a remaining element...
    const randIdx = Math.floor(Math.random() * curIdx);
    curIdx -= 1;

    // And swap it with the current element.
    const originalIdx = array[curIdx];
    array[curIdx] = array[randIdx];
    array[randIdx] = originalIdx;
  }
  return array;
}

// Usage of shuffle
const arr = [1, 2, 3, 4, 5, 6];
arr = shuffle(arr);
console.log(arr);

// shorter
function shuffle(array) {
    for (let i = array.length - 1; i > 0; i--) {
        var j = Math.floor(Math.random() * (i + 1));
        var originalIdx = array[i];
        array[i] = array[j];
        array[j] = originalIdx;
    }
}

//es6
function shuffle_array(array) {
    for (let i = array.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [array[i], array[j]] = [array[j], array[i]];
    }
}
const shuffleArray = array => {
  for (let i = array.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    const temp = array[i];
    array[i] = array[j];
    array[j] = temp;
  }
}
const array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const shuffledArray = array.sort((a, b) => 0.5 - Math.random());

// using Array map and Math.random
const shuffledArr = array => array.map(a => ({ sort: Math.random(), value: a })).sort((a, b) => a.sort - b.sort).map(a => a.value);

var element = document.querySelectorAll('.elementClass');
if (typeof(element) != 'undefined' && element != null) {
    //your code here
}
star

Tue Jun 22 2021 12:48:17 GMT+0000 (UTC)

#javascript #vanilla
star

Tue Jun 22 2021 08:15:53 GMT+0000 (UTC)

#javascript #vanilla #array
star

Fri Mar 05 2021 12:13:19 GMT+0000 (UTC)

#js #vanilla

Save snippets that work with our extensions

Available in the Chrome Web Store Get Firefox Add-on Get VS Code extension