javascript find first in array code example

Example 1: javascript find

const inventory = [
  {name: 'apples', quantity: 2},
  {name: 'cherries', quantity: 8}
  {name: 'bananas', quantity: 0},
  {name: 'cherries', quantity: 5}
  {name: 'cherries', quantity: 15}
  
];

const result = inventory.find( ({ name }) => name === 'cherries' );

console.log(result) // { name: 'cherries', quantity: 5 }

Example 2: javascript take first element of array

const array = [1,2,3,4,5];
const firstElement = array.shift();

// array -> [2,3,4,5]
// firstElement -> 1

Example 3: get first element of array javascript

// Method - 1 ([] operator)
var arr = [1, 2, 3, 4, 5];
var first = arr[0];
console.log(first);
/*
    Output: 1
*/

// Method - 2 (Array.prototype.shift())
var arr = [1, 2, 3, 4, 5];
var first = arr.slice(0, 1).shift();
console.log(first);
/*
    Output: 1
*/

// Method - 3 (Destructuring Assignment)
var arr = [1, 2, 3, 4, 5];
const [first] = arr;
console.log(first);
/*
    Output: 1
*/

Example 4: find method javascript

const inventory = [
  {name: 'apples', quantity: 2},
  {name: 'bananas', quantity: 0},
  {name: 'cherries', quantity: 5}
];

function isCherries(fruit) { 
  return fruit.name === 'cherries';
}

console.log(inventory.find(isCherries)); 
// { name: 'cherries', quantity: 5 }

Example 5: js get first item from array

var colors = ["red", "green", "blue"];
var red=colors.shift();
//colors is now ["green","blue"];

Example 6: javascript get first element of array

let mylist = ['one','two','three','last']
mylist[0],mylist[1],mylist[2],mylist[3]//this is called indexing and slicing in python
//in javascript it called getting elements in array