Snippets Collections
array_multisort(array_map(function($element) {
  return $element['key'];
}, $result), SORT_ASC, $result);
const arr = [1, 2, 3, 4];

// bad
const first = arr[0];
const second = arr[1];

// good
const [first, second] = arr;
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' },
//   ...
// ]
import React from 'react';

const people = [
  {
    name: 'James',
    age: 31,
  },
  {
    name: 'John',
    age: 45,
  },
  {
    name: 'Paul',
    age: 65,
  },
  {
    name: 'Ringo',
    age: 49,
  },
  {
    name: 'George',
    age: 34,
  }
];

function App() {
  return (
    <div>
      {people.filter(person => person.age < 60).map(filteredPerson => (
        <li>
          {filteredPerson.name}
        </li>
      ))}
    </div>
  );
}

export default App;
import React from 'react';

const names = ['James', 'John', 'Paul', 'Ringo', 'George'];

function App() {
  return (
    <div>
      {names.filter(name => name.includes('J')).map(filteredName => (
        <li>
          {filteredName}
        </li>
      ))}
    </div>
  );
}

export default App;
// This is what I've been using, pretty straight forward
// It passes the JSON to the children as props
// Of course, you fetch what you will
 
import React, { Component, Fragment } from 'react';
 
export class FetchJsonController extends Component
{
	constructor(props) {
		super(props);
		this.state = {
			data: null,
		};
	}
 
	componentDidMount() {
		fetch(this.props.src)
			.then(response => response.json())
			.then(data => {
				console.log(data);
				this.setState({ data })
			});
	}
 
	render() {
		const _data = this.state.data;
		const children = React.Children.map(this.props.children, child => {
			return React.cloneElement(child, {
				jsonData: _data
			});
		});
		return (
			<div>{ children }</div>
		)
	}
}
 
// This is how it's used
// SomeCompnent will receive the JSON data
<FetchJsonController src="somefile.json">
  <SomeComponent />
</FetchJsonController>
//What are pure functions?
//Pure functions take an input value (a parameter or argument) and produce an output value. //Like with hashing, the same input it will always return the same output 

const myPureFunction = number => return number * 4

//Pure functions must:
//1. Contain no side effects
//2. When given the same input, return the same output.
// A pure component avoids any use of state.
map
filter
reduce
import React, { Component } from "react";

class IconList extends Component {
  static defaultProps = {
    options: [
      "angry",
      "anchor",
      "archive",
      "at",
      "archway",
      "baby",
      "bell",
      "bolt",
      "bone",
      "car",
      "city",
      "cloud",
      "couch"
    ]
  };
  constructor(props) {
    super(props);
    this.state = { icons: ["bone", "cloud"] };
    this.addIcon = this.addIcon.bind(this);
  }
  //DON'T DO THIS!!!!
  // addIcon() {
  //   let idx = Math.floor(Math.random() * this.props.options.length);
  //   let newIcon = this.props.options[idx];
  //   let icons = this.state.icons;
  //   icons.push(newIcon);
  //   this.setState({ icons: icons });
  // }

  addIcon() {
    // get random index
    let idx = Math.floor(Math.random() * this.props.options.length);
 	// get new element
    let newIcon = this.props.options[idx];
    // update the state of the icons array (spread icons into new array, add new icon to it)
    this.setState({ icons: [...this.state.icons, newIcon] });
  }
  render() {
    // render newly mapped icons array
    const icons = this.state.icons.map(i => <i className={`fas fa-${i}`} />);
    return (
      <div>
        <h1>Icons: {icons}</h1>
        <button onClick={this.addIcon}>Add New Icon</button>
      </div>
    );
  }
}

export default IconList;
<?php
$url = "https://graph.instagram.com/me/media?access_token=IGQVJWVGM5azZApYkEwTENxQ19kbWdmS1dfeWxJcUk2VzJobF92LWE5NTdsNlV0dGFoNGw2bkRMZATh2SnFzcGVOeDJXNVNzcUoyS3pOY2taZA3BfX25sUHA3VXVHUlBTNFVGVHp1aEktOUxXbDlpV3cxeAZDZD&fields=media_url,media_type,caption,permalink";
// create curl resource
$ch = curl_init();

// set url
curl_setopt($ch, CURLOPT_URL, $url);

//return the transfer as a string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

// $output contains the output string
$instagramData = curl_exec($ch);
// close curl resource to free up system resources
curl_close($ch); 

$instagramData = json_decode($instagramData, true); // true = to array έστω
$instagramData = $instagramData['data'];

$tpl = 'instagramFeedTPL';
$out = '';

foreach ($instagramData as $data)
{
    if ($data['media_type'] == 'VIDEO')
    {
        $data['isVideo'] = 1;
    }
    
    $out .= $modx->getChunk($tpl, $data);
}


return $out;
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);

let clickMe = document.querySelector('button');

function getRandomNumber(min, max) {
  let totalEle = max - min + 1;
  let result = Math.floor(Math.random() * totalEle) + min;
  return result;
}
function createArrayOfNumber(start, end) {
  let myArray = [];
  for (let i = start; i <= end; i++) {
    myArray.push(i);
  }
  return myArray;
}
let numbersArray = createArrayOfNumber(1, 10);

clickMe.addEventListener('click', () => {
  if (numbersArray.length === 0) {
    console.log('No more random number');
    return;
  }
  let randomIndex = getRandomNumber(0, numbersArray.length - 1);
  let randomNumber = numbersArray[randomIndex];
  numbersArray.splice(randomIndex, 1);
  console.log(randomNumber);
});
let items = [1,25,"JavaScript",69,"css","34","keep coding","html"];
console.log(items)

//shuffle array
function shuffle(arr){
  for(let i =arr.length-1;i>0;i--){
    const j = Math.floor(Math.random() * (i+1));
    [arr[i],arr[j]] = [arr[j],arr[i]];
  }
  return arr
}
console.log(shuffle(items))

//shuffle selected index 
const  itemToShuffle = items.slice(3,7);
console.log(shuffle(itemToShuffle))

//items after shuffling item from index 3 to 7
items = [items[0],items[1],items[2],...itemToShuffle,items[7]]
console.log(items)
const arr = [333,1,2,11,22,3,4]
console.log(arr.sort())

arr.sort((a,b)=>a-b)

console.log(arr)
const arr = ["Apple",45,"","google",null],,,,"facebook","",69]

const removeEle = arr.filter((el)=> return el !=null && el != "")
function isEqual(arr1,arr2){
  let x = arr1.length;
  let y = arr2.lenght;
  
  //if lenght of array are not equal means array are not equal 
  if(x !=  y) return false;
  
  //sorting both array
  x.sort();
  y.sort();
  
  // Linearly compare elements
  for(let i=0;i<x;i++){
    if(x[i] != y[i]) return false
  }
  // If all elements were same.
    return true
}

let arrayOne = [3, 5, 2, 5, 2]
let arrayTwo = [2, 3, 5, 5, 2]

isEqual(arrayOne,arrayTwo) ? console.log("Matched") : console.log("Not Match")
$oneDimensionalArray = array_map('current', $twoDimensionalArray);

/*
current() function returns the value of the current element in an array. for ex : $fruits = array("banana", "apple", "orange"); echo current($fruits) //will return "banana" since current pointer is on index 0 which is banana
*/
 const arr = ["This", "Little", "Piggy"];
const first = arr.slice(0, 1);
const the_rest = arr.slice(1);console.log(first); // ["This"]
console.log(the_rest); // ["Little", "Piggy"]                               
                                
for (int i = 0; i < n; i++)
{
    if (valCount.ContainsKey(x))
        valCount[x]++;
    else
        valCount[x] = 1;
}
itemList.stream()
          .filter(item -> item.getPropertyList()
                         .stream().anyMatch(property -> property.getKey().equals("Test")))
           .collect(Collectors.toList());
star

Thu Sep 16 2021 08:36:20 GMT+0000 (UTC)

#php #sort #array
star

Thu Aug 19 2021 17:17:11 GMT+0000 (UTC) https://github.com/airbnb/javascript

#array
star

Sun Jul 04 2021 13:14:30 GMT+0000 (UTC) https://www.samanthaming.com/tidbits/87-5-ways-to-append-item-to-array/

#array #javscript
star

Tue Jun 29 2021 09:34:54 GMT+0000 (UTC) https://upmostly.com/tutorials/react-filter-filtering-arrays-in-react-with-examples

#array #react.js #javascript #react #filter #map
star

Thu Jun 24 2021 16:18:30 GMT+0000 (UTC)

#array #destructuring #javasc #react.js
star

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

#javascript #vanilla #array
star

Fri Apr 16 2021 07:42:52 GMT+0000 (UTC) https://playcode.io/757523/

#javascript #array #random #randomarray #dom
star

Thu Apr 08 2021 10:16:24 GMT+0000 (UTC) https://playcode.io/754960/

#javascript #array #shuffle
star

Fri Apr 02 2021 08:01:12 GMT+0000 (UTC)

#javascript #array #sort
star

Fri Apr 02 2021 06:52:39 GMT+0000 (UTC)

#javascript #array
star

Mon Nov 30 2020 14:23:00 GMT+0000 (UTC) https://stackoverflow.com/questions/8754980/how-to-convert-two-dimensional-array-to-one-dimensional-array-in-php5

#php #array
star

Fri Apr 24 2020 11:44:23 GMT+0000 (UTC) https://css-tricks.com/snippets/javascript/getting-first-and-last-items-in-array-and-splitting-all-the-rest/

#css #css #items #array
star

Wed Apr 01 2020 08:37:24 GMT+0000 (UTC) https://stackoverflow.com/questions/60966491/how-to-clear-item-not-input-when-count-frequency-use-dictionary-c-sharp

#C# #c# #array #dictionary
star

Wed Apr 01 2020 08:28:49 GMT+0000 (UTC) https://stackoverflow.com/questions/60966469/how-to-find-an-element-in-array-of-object-with-streams

#java #java #stream #array

Save snippets that work with our extensions

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